Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-字符串不能转换为int_Java_Compiler Errors - Fatal编程技术网

Java-字符串不能转换为int

Java-字符串不能转换为int,java,compiler-errors,Java,Compiler Errors,我有一个12个月的温度文本文件。 但是当我试图找到平均温度时,我得到了一个错误“String不能转换为int” temp[计数器]=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();

我有一个12个月的温度文本文件。 但是当我试图找到平均温度时,我得到了一个错误“String不能转换为int”

temp[计数器]=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);
Scanner sc=新扫描仪(新文件(“temperature.txt”);
int[]temp=新int[12];
int计数器=0;
while(sc.hasNextLine()){
temp[计数器]=sc.nextLine();
计数器++;
}
整数和=0;
对于(int i=0;i
Scanner::nextLine返回一个字符串。在Java中,不能像隐式转换那样将字符串转换为int

试一试


您需要将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 sc=新扫描仪(新文件(“temperature.txt”);
int[]temp=新int[12];
int计数器=0;
while(sc.hasNextLine()){
字符串行=sc.nextLine();
temp[计数器]=整数.ParseInt(行);
计数器++;
}
整数和=0;
对于(int i=0;i
您的sc.nextLine()返回字符串


嗯,是的
sc.nextLine()
返回一个
字符串
,您试图将其指定为
int
数组中的元素。现在还不清楚你是怎么想的。也许您应该使用
sc.nextInt()
Integer.ParseInt(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);
  }
}