Java - String无法转换为int

时间:2016-09-22 12:17:45

标签: java compiler-errors

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

  

temp [counter] = sc.nextLine();

有人能说出错是什么意思吗?

griddata

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您需要将 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);
  }
}

答案 2 :(得分:0)

相关问题