“字符串不能转换为int”

这个问题在这里已经有了答案:

  • 如何在Java中将字符串转换为int? 30个答案

  • 您需要将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返回一个字符串。 在Java中,您不能像隐式地将String转换为int。

    尝试

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

    你的sc.nextLine()返回String

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

    链接地址: http://www.djcxy.com/p/20917.html

    上一篇: "String cannot be converted to int"

    下一篇: Convert a string value into an int