“字符串无法转换为int”

我有一个温度来自所有12个月的文本文件。 但是当我试图找到平均温度时,我得到错误“String无法转换为int”到该行

temp [counter] = 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); 

您需要将sc.nextLine转换为int

  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); } } 

Scanner :: nextLine返回一个String。 在Java中,您不能像隐式执行那样将String转换为int。

尝试

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