Java-字符串不能转换为int [英] Java - String cannot be converted to int

查看:126
本文介绍了Java-字符串不能转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,列出了所有12个月的温度。
但是,当我尝试找到平均温度时,在行中出现错误无法将字符串转换为int

I have a textfile with temperatures from all 12 months. But when I try to find the average temperature, I get the error "String cannot be converted to int" to the line


temp [counter] = sc.nextLine();

temp[counter] = sc.nextLine();

有人可以说出什么问题吗?

Can someone say what's wrong?

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆