2016-02-28 34 views
0

我正在編寫一個代碼,應該將考試分數作爲輸入,直到用戶輸入'-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 

所有幫助和建議表示讚賞!

+0

'in.nextInt();' – Eran

+0

哦,我的上帝,我不相信我錯過了一些跛腳的東西。謝謝 –

+0

修復in.nextInt()後,您的代碼將無法編譯。在方法中添加return語句! – FallAndLearn

回答

2

nextInt是一種方法,而不是數據成員 - 它應該用圓括號調用:nextInt()

0

由Mureinik提供的答案是正確的。當你編寫任何Java程序時,如果你得到編譯時錯誤或運行時異常,試着看看錯誤或異常日誌提到的信息是什麼。在你所提到的情況下,顯然它說

hw6.java:14: error: cannot find symbol 
     int scoreIn = in.nextInt; 
        ^
    symbol: variable nextInt 
    location: variable in of type Scanner 
1 error 
  1. 問題是行號14:看到代碼的行數你 編譯。
  2. 問題是什麼? :cannot find symbol
  3. 找不到哪個符號? :nextInt
  4. 在哪個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有關。 希望這有助於您未來的編碼。