2016-09-22 6 views
0

모든 12 개월의 온도를 가진 텍스트 파일이 있습니다. 하지만 평균 온도를 찾을 때, 나는 오류가 라인"문자열을 int로 변환 할 수 없습니다"

온도 [카운터] = sc.nextLine()에 "문자열이 int로 변환 할 수 없습니다";

무엇이 잘못되었는지 보는 사람이 있습니까?

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

잘 문자열을 반환 yes ...'sc.nextLine()'은'String'을 리턴합니다. 여러분은'int' 배열의 요소로 그것을 할당하려고합니다. 어떻게 예상했는지는 분명치 않습니다. 아마 당신은'sc.nextInt()'를 사용해야할까요? –

+7

'Integer.ParseInt (sc.nextLine())' – SimpleGuy

+0

문자열을 int 배열에 넣으려고합니다. – lubilis

답변

1

당신은 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); 
    } 
} 
1

Scanner :: nextLine은 String을 반환합니다. Java에서는 암시 적으로 String처럼 int로 캐스팅 할 수 없습니다.

temp[counter] = Integer.parseInt(sc.nextLine()); 
관련 문제