Corinne Java Question (It takes too long to execute)

Asked 2 years ago, Updated 2 years ago, 22 views

It's a question of taking an integer value from a text file and outputting 1. how many values are in it, 2. what is their average, and 3. values that are greater than the average. I wrote the code like this because the question said that the file should be opened and closed three times.

There is no error message in the column you are creating, but if you press the Run button to run it, the execution will not end no matter how long you wait. Loading? It feels like that. No matter how long I wait, it never ends. What's the problem?ㅠ<

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

}

java

2022-09-20 19:47

1 Answers

If you only use hasNextInt(), the program does not end because it only checks for the next value and does not move on, so it keeps checking in the same place.

Please add input1.nextInt() within the while statement.

while(input1.hasNextInt()) {
    count++;
    System.out.println(input1.nextInt());
}


2022-09-20 19:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.