2016-09-22 118 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());