java 找不到标志
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5517708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot find symbol
提问by edwinNosh
I'm getting the following java compiler errors:
我收到以下 Java 编译器错误:
main.java:9: cannot find symbol
symbol : method parseInt(int)
location: class java.lang.Integer
int count = Integer.parseInt(getPennies());
^
main.java:23: incompatible types
found : java.lang.String
required: int
JOptionPane.showInputDialog("How many pennies do you have?");
^
2 errors
2 错误
Here is my code
这是我的代码
import javax.swing.*;
class main {
public static void main(String args[]) {
try {
int count = Integer.parseInt(getPennies());
System.out.println("You have "+count+" pennies");
} catch (NumberFormatException exception) {
System.out.println("Please insert a number");
getPennies();
}
}
public static int getPennies() {
int input =
JOptionPane.showInputDialog("How many pennies do you have?");
return input;
}
}
Any idea why I am getting these errors?
知道为什么我会收到这些错误吗?
回答by Jon Skeet
Well, getPennies()
returns an int
, and there's no such method as Integer.parseInt(int)
- the idea is that parseInt
parses a string and givesyou an integer.
好吧,getPennies()
返回一个int
,并且没有这样的方法Integer.parseInt(int)
- 这个想法是parseInt
解析一个字符串并给你一个整数。
Then later you have:
然后你有:
int input = JOptionPane.showInputDialog("How many pennies do you have?");
... but showInputDialog returns a string, not an integer.
...但 showInputDialog 返回一个字符串,而不是一个整数。
You could fix both of these problems by changing getPennis() like this:
您可以通过像这样更改 getPennis() 来解决这两个问题:
public static String getPennies() {
return JOptionPane.showInputDialog("How many pennies do you have?");
}
Or:
或者:
public static int getPennies() {
String text = JOptionPane.showInputDialog("How many pennies do you have?");
return Integer.parseInt(text);
}
and removing the call to Integer.parseInt
from the callerof getPennies()
.
和取出呼叫Integer.parseInt
从主叫方的getPennies()
。
回答by Alex
The method JOptionPane.showInputDialog()
returns a String
and not an int
.
该方法JOptionPane.showInputDialog()
返回 aString
而不是 an int
。
So you have a type incompatibility issue.
所以你有一个类型不兼容的问题。
回答by Evan Mulawski
Integer.parseInt
requires a String
input, not an int
. Just use getPennies()
without it. For the second error, showInputDialog
returns a String
, so use the parseInt
function there instead.
Integer.parseInt
需要String
输入,而不是int
. getPennies()
不用它就可以使用。对于第二个错误,showInputDialog
返回 a String
,因此请改用该parseInt
函数。
回答by rsp
The parseInt()
method parses a string to an integer, the input is done as a string, so changing the return type of getPennies()
to a String
will probably do the job.
该parseInt()
方法将字符串解析为整数,输入作为字符串完成,因此将返回类型更改getPennies()
为 aString
可能会完成这项工作。