Method call expected java ошибка

This is a java program with two buttons used to change an integer value and display it.
However in IntelliJIDEA the two lines with

increase.addActionListener(incListener());
decrease.addActionListener(decListener());

keep displaying errors ‘Method call expected’.

I am not sure what to do to fix this.

Any help will be greatly appreciated

Thanks

Note: the full code is attached below.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main extends JDialog {
public JPanel contentPane;
public JButton decrease;
public JButton increase;
public JLabel label;

public int number;

public Main() {
    setContentPane(contentPane);
    setModal(true);

    increase = new JButton();
    decrease = new JButton();
    increase.addActionListener(incListener());
    decrease.addActionListener(decListener());

    number = 50;
    label = new JLabel();
}

public class incListener implements ActionListener {
    public void actionPerformed (ActionEvent event) {
        number++;
        label.setText("" + number);
    }
}

public class decListener implements ActionListener {
    public void actionPerformed (ActionEvent event) {
        number--;
        label.setText("" + number);
    }
}

public static void main(String[] args) {
    Main dialog = new Main();
    dialog.pack();
    dialog.setVisible(true);
    System.exit(0);

}
}

asked May 7, 2013 at 11:45

Seb Welch's user avatar

1

incListener and declListener are classes, not methods.

Try

increase.addActionListener(new incListener());

btw, rename your classes names to make them start with an uppercase

answered May 7, 2013 at 11:47

Arnaud Denoyelle's user avatar

Arnaud DenoyelleArnaud Denoyelle

29.7k15 gold badges90 silver badges146 bronze badges

It’s simple: use new incListener() instead of incListener(). The later is trying to call a method named incListener, the former creates an object from the class incListener, which is what we want.

answered May 7, 2013 at 11:48

PurkkaKoodari's user avatar

PurkkaKoodariPurkkaKoodari

6,6936 gold badges37 silver badges57 bronze badges

incListener and decListener are a classes but not a methods, so you must call new to use them, try this:

increase.addActionListener(new incListener());
decrease.addActionListener(new decListener());

sorry for my bad english

answered May 7, 2013 at 11:53

Manitra's user avatar

substitute the lines with

increase.addActionListener( new incListener());
decrease.addActionListener( new decListener());

answered May 7, 2013 at 11:47

Simulant's user avatar

SimulantSimulant

19k8 gold badges62 silver badges98 bronze badges

Make these changes:

 public Main() {
    contentPane = new JPanel();
    setContentPane(contentPane);
    setModal(true);

    increase = new JButton("inc");
    decrease = new JButton("dec");
    contentPane.add(increase);
    contentPane.add(decrease);
    increase.addActionListener(new incListener());
    decrease.addActionListener(new decListener());

    number = 50;
    label = new JLabel(number+"");
    contentPane.add(label);
}

answered May 7, 2013 at 11:55

hamid's user avatar

hamidhamid

2,0154 gold badges22 silver badges42 bronze badges

It’s sad but I had to Google this same error… I was staring at a method that returned a class. I left off the new operator.

return <class>(<parameters>)
vs
return new <class>(<parameters>)

answered May 20, 2019 at 17:56

Cory's user avatar

CoryCory

1962 silver badges8 bronze badges

Whenever a string object is created using new operator a new object is created which is what your program is looking for.
The following link is useful in learning about the difference between a string and a new string.
What is the difference between «text» and new String(«text»)?

answered Jul 9, 2018 at 20:03

Vikas Singh's user avatar

Передача данных из класса, принадлежащего суперклассу. Method call expected

День добрый.
IDE ругается и говорит, что Method call expected.
я не могу понять в чём проблема. про ошибку почитал и про toString прочитал, но не могу понять в чём затык. подскажите пожалуйста как решить этот вопрос.
да, ещё. пробовал сделать геттеры, но их даёт создать только в суперклассе. и из него, естественно, передаются только пустые поля, т.к. в суперклассе нет данных по умолчанию

package com.javarush.task.task05.task0526;

/*
Мужчина и женщина
*/

public class Solution {

public static void main(String[] args) {
Man man1 = new Man(«Vasya», 25, «Moscow»);
Man man2 = new Man(«Petruha», 30, «Groznyi» );
Woman woman1 = new Woman(«Gulfira», 24, «Bangladesh»);
Woman woman2 = new Woman(«Fatima», 34, «Tegeran»);
System.out.println(man1);
System.out.println(man2);
System.out.println(woman1);
System.out.println(woman2);
}

static class Human {//create super class parent`s class must be static too
private String name;
private int age;
private String address;
Human (String name, int age, String address){//create constructor
}
}

public static class Man extends Human {
Man (String name, int age, String address){
super(name, age, address); }

public String toString() {
return Man().getName() + » » + Man().getAge() + » » + Man().getAddress();
}
}

public static class Woman extends Human {
Woman (String name, int age, String address){
super(name, age, address); }

public String toString() {
return Woman().getName() + » » + Woman().getAge() + » » + Woman().getAddress();
}

}

}

Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.

EditText username = (EditText)LoginActivity().findViewById(R.id.txtuser);

showing this error Method Call Expected on android studio.

What I have tried:

Showing Method Call expected on

LoginActivity()

What should I do to get rid out of this, actually I want to pass the EditText parameter to WCF sercvices, Thats why I am using this line, Is it correct?

Updated 21-Aug-17 17:51pm

Comments

Current page… i.e.LoginActivity.java

Do you actually understand the difference between a source file and an object or method in the program?


1 solution

Solution 1

Quote:

actually I want to pass the EditText parameter to WCF sercvices,

This is the way how you pass the editText value.

First, initialize your editText

EditText username = (EditText)findViewById(R.id.txtuser);

After that, get the username value

String name = username.getText().toString();

Then only pass the name to WCF sercvices

Kubson

8 / 2 / 0

Регистрация: 17.07.2014

Сообщений: 253

1

31.03.2016, 20:20. Показов 8415. Ответов 11

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
private final static BigInteger one      = new BigInteger("1");
    private final static SecureRandom random = new SecureRandom();
 
    private BigInteger privateKey;
    private BigInteger publicKey;
    private BigInteger modulus;
 
    public void init(int N) {
        BigInteger p = BigInteger.probablePrime(N/2, random);
        BigInteger q = BigInteger.probablePrime(N/2, random);
        BigInteger phi = (p.subtract(one)).multiply(q.subtract(one));
 
        modulus    = p.multiply(q);
 
        privateKey = publicKey.modInverse(phi);
    }
 
    public void setPrivateKey(BigInteger privateKey) {
        this.privateKey = privateKey;
    }
 
    public void setPublicKey(BigInteger publicKey) {
        this.publicKey = publicKey;
    }
 
    public void setModulus(BigInteger modulus) {
        this.modulus = modulus;
    }
 
    public BigInteger getPrivateKey() {
        return privateKey;
    }
 
    public BigInteger getPublicKey() {
        return publicKey;
    }
 
    public BigInteger getModulus() {
        return modulus;
    }
 
    // generate an N-bit (roughly) public and private key
 
             // common value in practice = 2^16 + 1
 
    BigInteger encrypt(BigInteger message) {
        return message.modPow(publicKey, modulus);
    }
 
    BigInteger decrypt(BigInteger encrypted) {
        return encrypted.modPow(privateKey, modulus);
    }
 
    public String toString() {
        String s = "";
        s += "public  = " + publicKey  + "n";
        s += "private = " + privateKey + "n";
        s += "modulus = " + modulus;
 
        return s;
    }
protected void onCreate(Bundle savedInstanceState) {
        int N = 1024; //количество бит для генерации RSA ключей
        WhatTheHellAreYouDoingInMyCode rsa = new WhatTheHellAreYouDoingInMyCode();
        rsa.init(N);
        BigInteger message = new BigInteger("Привет Мир! I love you!".getBytes());
        rsa.setModulus(modulus); //используем modulus, который получили от сервера
        rsa.setPublicKey(publicKey); //используем publicKey, который получили от сервера
        BigInteger encryptMessage = rsa.encrypt(message);
        BigInteger decryptMessage = rsa.decrypt(encryptMessage);
        System.out.println( new String(decryptMessage().getBytes()));

В последней строчке кода ошибка «Method call expected» и красным подчеркнуто decryptMessage(). Как мне это исправить??? Помогите пожалуйста!

Спасибо за внимание!



0



YuraAAA

1605 / 1337 / 291

Регистрация: 25.10.2009

Сообщений: 3,487

Записей в блоге: 2

31.03.2016, 21:05

2

Kubson,

Java
1
decryptMessage.getBytes()

.
Лишние скобки



1



8 / 2 / 0

Регистрация: 17.07.2014

Сообщений: 253

01.04.2016, 20:17

 [ТС]

3

YuraAAA, я убрал скобки, но ничего не изменилось



0



1605 / 1337 / 291

Регистрация: 25.10.2009

Сообщений: 3,487

Записей в блоге: 2

01.04.2016, 20:37

4

Kubson, ну покажите что получилось



0



8 / 2 / 0

Регистрация: 17.07.2014

Сообщений: 253

02.04.2016, 09:51

 [ТС]

5

YuraAAA, я ж говорю, ничего не изменилось: все та же ошибка на том же месте. Новых ошибок не прибавилось.



0



2882 / 2294 / 769

Регистрация: 12.05.2014

Сообщений: 7,978

02.04.2016, 11:34

6

тебя ведь попросили показать код после того как убрал скобки



0



Kubson

8 / 2 / 0

Регистрация: 17.07.2014

Сообщений: 253

02.04.2016, 13:59

 [ТС]

7

Паблито,

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
private final static BigInteger one      = new BigInteger("1");
    private final static SecureRandom random = new SecureRandom();
 
    private BigInteger privateKey;
    private BigInteger publicKey;
    private BigInteger modulus;
 
    public void init(int N) {
        BigInteger p = BigInteger.probablePrime(N/2, random);
        BigInteger q = BigInteger.probablePrime(N/2, random);
        BigInteger phi = (p.subtract(one)).multiply(q.subtract(one));
 
        modulus    = p.multiply(q);
 
        privateKey = publicKey.modInverse(phi);
    }
 
    public void setPrivateKey(BigInteger privateKey) {
        this.privateKey = privateKey;
    }
 
    public void setPublicKey(BigInteger publicKey) {
        this.publicKey = publicKey;
    }
 
    public void setModulus(BigInteger modulus) {
        this.modulus = modulus;
    }
 
    public BigInteger getPrivateKey() {
        return privateKey;
    }
 
    public BigInteger getPublicKey() {
        return publicKey;
    }
 
    public BigInteger getModulus() {
        return modulus;
    }
 
    // generate an N-bit (roughly) public and private key
 
             // common value in practice = 2^16 + 1
 
    BigInteger encrypt(BigInteger message) {
        return message.modPow(publicKey, modulus);
    }
 
    BigInteger decrypt(BigInteger encrypted) {
        return encrypted.modPow(privateKey, modulus);
    }
 
    public String toString() {
        String s = "";
        s += "public  = " + publicKey  + "n";
        s += "private = " + privateKey + "n";
        s += "modulus = " + modulus;
 
        return s;
    }
protected void onCreate(Bundle savedInstanceState) {
        int N = 1024; //количество бит для генерации RSA ключей
        WhatTheHellAreYouDoingInMyCode rsa = new WhatTheHellAreYouDoingInMyCode();
        rsa.init(N);
        BigInteger message = new BigInteger("Привет Мир! I love you!".getBytes());
        rsa.setModulus(modulus); //используем modulus, который получили от сервера
        rsa.setPublicKey(publicKey); //используем publicKey, который получили от сервера
        BigInteger encryptMessage = rsa.encrypt(message);
        BigInteger decryptMessage = rsa.decrypt(encryptMessage);
        System.out.println( new String(decryptMessage().getBytes));



0



2882 / 2294 / 769

Регистрация: 12.05.2014

Сообщений: 7,978

02.04.2016, 14:01

8

вообще не читаешь что пишут люди?
где там убраны скобки как предложил YuraAAA ?



0



1605 / 1337 / 291

Регистрация: 25.10.2009

Сообщений: 3,487

Записей в блоге: 2

02.04.2016, 14:14

9

Паблито, он убрал у getBytes метода скобки

Добавлено через 21 секунду
Kubson,

Цитата
Сообщение от Kubson
Посмотреть сообщение

decryptMessage.getBytes()

должно быть так



0



8 / 2 / 0

Регистрация: 17.07.2014

Сообщений: 253

02.04.2016, 16:09

 [ТС]

10

Ах да, спасибо что помогли с этим, но теперь возникла новая ошибка: Error144, 54) error: cannot find symbol method getBytes()

Добавлено через 1 час 2 минуты
Я исправил ее, и вновь появилась новая 04-02 16:08:28.791 5411-5411/spsoft.passwordgenerator E/AndroidRuntime: FATAL EXCEPTION: main
Process: spsoft.passwordgenerator, PID: 5411
java.lang.RuntimeException: Unable to start activity ComponentInfo{spsoft.passwordgenerator/spsoft.passwordgenerator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘java.math.BigInteger java.math.BigInteger.modInverse(java.math.BigInteger)’ on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2790)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2855)
at android.app.ActivityThread.access$900(ActivityThread.java:181)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1474)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6117)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘java.math.BigInteger java.math.BigInteger.modInverse(java.math.BigInteger)’ on a null object reference
at spsoft.passwordgenerator.MainActivity.init(MainActivity.java:70)
at spsoft.passwordgenerator.MainActivity.onCreate(MainActivity.java:138)
at android.app.Activity.performCreate(Activity.java:6374)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2743)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2855)*
at android.app.ActivityThread.access$900(ActivityThread.java:181)*
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1474)*
at android.os.Handler.dispatchMessage(Handler.java:102)*
at android.os.Looper.loop(Looper.java:145)*
at android.app.ActivityThread.main(ActivityThread.java:6117)*
at java.lang.reflect.Method.invoke(Native Method)*
at java.lang.reflect.Method.invoke(Method.java:372)*
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) *
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)*
Ошибка здесь: privateKey = publicKey.modInverse(phi);

Как же мне ее исправить?..



0



1605 / 1337 / 291

Регистрация: 25.10.2009

Сообщений: 3,487

Записей в блоге: 2

02.04.2016, 17:21

11

Лучший ответ Сообщение было отмечено Kubson как решение

Решение

Kubson,

Цитата
Сообщение от Kubson
Посмотреть сообщение

BigInteger java.math.BigInteger.modInverse(java.math.BigInteger)’ on a null object reference



1



8 / 2 / 0

Регистрация: 17.07.2014

Сообщений: 253

02.04.2016, 18:46

 [ТС]

12

YuraAAA, спасибо большое!



0



This is a java program with two buttons used to change an integer value and display it.
However in IntelliJIDEA the two lines with

increase.addActionListener(incListener());
decrease.addActionListener(decListener());

keep displaying errors ‘Method call expected’.

I am not sure what to do to fix this.

Any help will be greatly appreciated

Thanks

Note: the full code is attached below.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main extends JDialog {
public JPanel contentPane;
public JButton decrease;
public JButton increase;
public JLabel label;

public int number;

public Main() {
    setContentPane(contentPane);
    setModal(true);

    increase = new JButton();
    decrease = new JButton();
    increase.addActionListener(incListener());
    decrease.addActionListener(decListener());

    number = 50;
    label = new JLabel();
}

public class incListener implements ActionListener {
    public void actionPerformed (ActionEvent event) {
        number++;
        label.setText("" + number);
    }
}

public class decListener implements ActionListener {
    public void actionPerformed (ActionEvent event) {
        number--;
        label.setText("" + number);
    }
}

public static void main(String[] args) {
    Main dialog = new Main();
    dialog.pack();
    dialog.setVisible(true);
    System.exit(0);

}
}

incListener and declListener are classes, not methods.

Try

increase.addActionListener(new incListener());

btw, rename your classes names to make them start with an uppercase

It’s simple: use new incListener() instead of incListener(). The later is trying to call a method named incListener, the former creates an object from the class incListener, which is what we want.

incListener and decListener are a classes but not a methods, so you must call new to use them, try this:

increase.addActionListener(new incListener());
decrease.addActionListener(new decListener());

sorry for my bad english

Понравилась статья? Поделить с друзьями:
  • Metatrader 4 общая ошибка
  • Metamask ошибка при получении котировок
  • Metamask обнаружил ошибку
  • Metal gear solid v the phantom pain ошибки
  • Metal gear rising revengeance ошибка при запуске