2016-09-22 89 views
0

我有一個12個月的溫度文本文件。 但是,當我試圖找到的平均溫度,我得到的錯誤「字符串不能被轉換爲int」到行「字符串不能轉換爲int」

溫度[計數器] = sc.nextLine();

有人誰看到有什麼問題?

Scanner sc = new Scanner(new File("temperatur.txt")); 
int[] temp = new int [12]; 
int counter = 0; 
while (sc.hasNextLine()) { 
    temp[counter] = sc.nextLine(); 
    counter++; 
} 

int sum = 0; 
for(int i = 0; i < temp.length; i++) { 
    sum += temp[i]; 
} 

double snitt = (sum/temp.length); 
System.out.println("The average temperature is " + snitt); 
+4

好yes ...'sc.nextLine()'返回一個'String',你試圖將它賦值爲一個'int'數組中的元素。目前還不清楚你如何預期這項工作。也許你應該使用'sc.nextInt()'? –

+7

'Integer.ParseInt(sc.nextLine())' – SimpleGuy

+0

你試圖把一個字符串放入一個int數組 – lubilis

回答

1

你需要轉換sc.nextLineINT

Scanner sc = new Scanner(new File("temperatur.txt")); 

     int[] temp = new int [12]; 
     int counter = 0; 

     while (sc.hasNextLine()) { 
      String line = sc.nextLine(); 
      temp[counter] = Integer.ParseInt(line); 
      counter++; 
     } 

     int sum = 0; 

     for(int i = 0; i < temp.length; i++) { 
      sum += temp[i]; 

    } 

    double snitt = (sum/temp.length); 

     System.out.println("The average temperature is " + snitt); 
    } 
} 
1

Scanner :: nextLine返回一個字符串。在Java中,您不能像隱式地將String轉換爲int。

嘗試

temp[counter] = Integer.parseInt(sc.nextLine());