关于编译器错误:String cannot be converted to int

Java - String cannot be converted to int

本问题已经有最佳答案,请猛点这里访问。

我有一个文本文件记录了12个月来的气温。但是当我试图找到平均温度时,我得到了错误"string cannot be converted to int"to the line

temp[counter] = sc.nextLine();

有人能说什么不对吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 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返回一个字符串。在爪哇中,不能像您隐式地将字符串转换成int。

尝试

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


sc.nextline()返回字符串

https://www.tutorialspoint.com/java/util/scanner_nextline.htm网站