3

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);
Steffi Keran Rani J
  • 3,667
  • 4
  • 34
  • 56

3 Answers3

3

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);
  }
}
Dsenese1
  • 1,106
  • 10
  • 18
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());
DaImmi
  • 121
  • 5
0

Your sc.nextLine() returns String

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

Johnny Five
  • 987
  • 1
  • 14
  • 29