JAVA-错误:找不到符号 - 在网站上还没有找到答案
问题描述:
我正在编写一个代码,应该将考试分数作为输入,直到用户输入'-1'。他们退出后,平均分数并打印出来。我不断收到'无法找到符号'的错误,并且我浏览了该网站,但还没有找到任何适用的东西。JAVA-错误:找不到符号 - 在网站上还没有找到答案
import java.util.*;
public class hw6
{
public static void main(String args[])
{
int avg = 0;
Scanner in = new Scanner(System.in);
System.out.println("This program will intake exam scores between 0 and 100 ONLY.");
System.out.println("Enter scores to average, and when you're done inputting, ");
System.out.println("enter -1 to stop and average your scores.");
int scoreIn = in.nextInt;
getLegalInput(scoreIn);
System.out.println("The average of the exam scores is " + avg + ".");
}
public static int getLegalInput (int scoreIn)
{
int sum = 0;
int i = 0;
while (scoreIn != -1)
{
if ((scoreIn < 101) && (scoreIn > -1))
{
sum = (sum + scoreIn);
i++;
}
else
System.out.println("Out of range! Must be between 0 and 100.");
}
if (scoreIn == -1)
{
CalcAvg(sum, i);
}
}
public static int CalcAvg(int sum, int i)
{
int avg = 0;
i = (i - 1); //fix problem where the stop value is included in the i value
//calc = (calc - Svalue); // fixes problem where stop value throws off the calc
avg = (sum/i); //averages the values of exam
return (avg);
}
}
我得到的错误是:
hw6.java:14: error: cannot find symbol
int scoreIn = in.nextInt;
^
symbol: variable nextInt
location: variable in of type Scanner
1 error
所有帮助和建议表示赞赏!
答
由Mureinik提供的答案是正确的。当你编写任何Java程序时,如果你得到编译时错误或运行时异常,试着看看错误或异常日志提到的信息是什么。在你所提到的情况下,显然它说
hw6.java:14: error: cannot find symbol
int scoreIn = in.nextInt;
^
symbol: variable nextInt
location: variable in of type Scanner
1 error
- 问题是行号14:看到代码的行数你 编译。
- 问题是什么? :
cannot find symbol
- 找不到哪个符号? :
nextInt
- 在哪个java类中找不到符号? :
Scanner.java
所以问题是:In Scanner.java there is no variable of type nextInt. We have written the code which tries to access nextInt variable from the object of class Scanner.
互联网上正确的搜索应该核实这个变量,然后你会才知道,这不是一个变量,但一个方法(函数 )等等而不是编写in.nextInt
它应该是in.nextInt()
另请注意,在Java中我们将函数称为方法。当你想要完成一些过程时,就像在目前的情况下,我们希望从输入流中读取一个整数,我们总是使用方法来完成它。通常我们只能从另一个类的对象中访问常量变量。为了与来自其他类的对象进行交互,我们应该使用方法。我们不在类之外暴露非常量字段[java语法允许,但是我们将方法作为外部世界的接口公开]。这与Encapsulation
有关。 希望这有助于您未来的编码。
'in.nextInt();' – Eran
哦,我的上帝,我不相信我错过了一些跛脚的东西。谢谢 –
修复in.nextInt()后,您的代码将无法编译。在方法中添加return语句! – FallAndLearn