Search code examples
javaloopsinputoutputinfinite-loop

Infinite loop with sc.hasNextLine()


I am trying to work with input, but I have trouble... if I use code bellow, it hasn't end... so I am in infinite loop. and it writes something like that, even when my input has end of file:

...
A number has not been parsed from line n
A number has not been parsed from line n+1
A number has not been parsed from line n+2
... (infinite)

but I wanna instead of that this:

...
End of input detected!

Input looks like that:

1
2
3
4
5
double[] numbers = new double[10];
int counter_number = 0;
while (sc.hasNextLine()) {
        ...
        line++;
        if(sc.hasNextDouble()) {
            numbers[counter_number] = sc.nextDouble();
            counter_number++;
        }
        else{
            System.out.println("A number has not been parsed from line "+ line);
            continue;
        }
        if (sc.hasNextLine() == false) {
            System.err.println("End of input detected!");
        }
        if (((counter_number)==10) || ((sc.hasNextLine() == false) 
                ...
            counter_number = 0;
        }
    }

while this loop never end? I saw tutorials where they used "while (sc.hasNextLine())" and it finished. I am beginner with java.


Solution

  • static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        double[] numbers = new double[10];
        int counter_number = 0;
        int line = 0;
    
        while (sc.hasNextLine()){
    
            line++;
    
            String thisLine = sc.nextLine();
            // this is what i wrote.
    
            if(thisLine.trim().isEmpty()) {
                // if the line is empty, will exit the loop.
    
                System.out.println("lines: "+line); // lines
                System.out.println("End of input detected!"); // end.
                break;
            }
    
            try {
                // if the input is a double
                numbers[counter_number] = Double.parseDouble(thisLine);
                counter_number++;
    
            } catch (NumberFormatException e) {
                // if not
                System.out.println("A number has not been parsed from line "+ line);
                continue;
            }
    
            // idk
            if (counter_number == numbers.length) {
                counter_number = 0;
            }
        };
    
    }
    

    FIX. I won't close the Scanner and... you try with this. This code end up when i type an empty line.