Java - String cannot be converted to int [duplicat

2019-03-03 09:46发布

问题:

This question already has an answer here:

  • How do I convert a String to an int in Java? 43 answers

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();

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);

回答1:

You need to convert sc.nextLine into 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);
  }
}


回答2:

Scanner::nextLine returns a String. In Java you can't cast a String to an int like you do implicitly.

try

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


回答3:

Your sc.nextLine() returns String

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