Java - 字符串无法转换为int

标签 java compiler-errors

我有一个包含所有 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);
  }
}

关于Java - 字符串无法转换为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39638851/

相关文章:

java - 将 char 添加到 int 而不会出现不兼容错误

linux - 我正在尝试编写一个 shell 命令来查找并编译所有 C 程序

java - 没有封闭实例错误

java - 使用javac在终端中编译Java程序时出错

Java程序计算变量数组的平均值,从命令行输入,显示结果

java - 从 ifconfig 获取 inet、bcast 和 mask

java - 查找最后发薪日期

java - 如何在 Mac 上以编程方式缩放 JFrame 窗口?

Java 对象数组在初始化期间崩溃

debugging - 找不到 -lasan 和 libasan_preinit.o