코린이 자바 질문 (실행이 너무 오래걸려요ㅠ)
조회수 514회
텍스트 파일에서 정수값을 받아서 1. 몇 개의 값이 들어가 있는지, 2. 그들의 평균은 무엇인지, 3. 평균보다 큰 값들 출력하는 문제입니다. 파일을 세 번 열고 닫고 해야 한다고 문제에 나와 있어서 이렇게 코드를 작성했습니다.
작성하는 란에는 따로 오류 메세지 같은 건 안 뜨는데 실행하려고 실행버튼 누르면 아무리 기다려도 실행한게 안 끝납니다. 로딩 중? 계속 그런 느낌이에요. 아무리 기다려도 절대 안 끝나는데 무엇이 문제인가요?ㅠㅠ
public static void main(String[] args) {
int count = 0;
Scanner input1 = null;
try {
input1 = new Scanner(new File("numbers.txt"));
} catch (Exception ex) {
System.out.println("Can not open file.");
System.exit(0);
}
while(input1.hasNextInt()) {
count++;
}
input1.close();
int sum = 0;
Scanner input2 = null;
try {
input2 = new Scanner(new File("numbers.txt"));
} catch (Exception ex) {
System.out.println("Can not open file.");
System.exit(0);
}
while(input2.hasNextInt()) {
int number = input2.nextInt();
sum += number;
}
input2.close();
double average = (double) sum / count;
int numbersAboveAverage;
System.out.println("The numbers above average are: ");
Scanner input3 = null;
try {
input3 = new Scanner(new File("numbers.txt"));
} catch (Exception ex) {
System.out.println("Can not open file.");
System.exit(0);
}
while(input3.hasNextInt()) {
int number = input3.nextInt();
if(number > average){
System.out.print(number + " ");
}
}
input3.close();
}
}
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
hasNextInt() 만 사용하면 다음에 값이 있는지 여부만 체크할 뿐 다음으로 넘어가지 않아서 계속 같은 자리에서 체크하기 때문에 프로그램이 종료되지 않습니다.
while문 내에 input1.nextInt() 를 추가해주시기 바랍니다.
- 프로그램이 종료되지 않는 것처럼 보이는 경우는 루프(while,for)문 안에 디버깅 코드(println)를 넣어서 어느 부분에서 문제가 발생하는지 확인해보시기 바랍니다.
while(input1.hasNextInt()) { count++; System.out.println(input1.nextInt()); }
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력