Java-字符串不能转换为int
我有一个12个月的温度文本文件。 但是当我试图找到平均温度时,我得到了一个错误“String不能转换为int” temp[计数器]=sc.nextLine() 有人能说什么不对吗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();
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);
}
}