Search code examples
javajava.util.scanneruser-input

Limit number of input lines in Java?


I have a problem where I want to take input from the user, the user can insert 1 and up to 8 lines, and each line represents a case. What I want is to stop the scanner when the user inserts 8 lines, Or if the user wants less than 8 he can press enter or a specific key to end the loop.

What I have done so far:

public static void doSomthing(){

    Scanner input = new Scanner(System.in);

    while (input.hasNextLine()) { // here I want to check so that it don't exeed 8 lines
        int e;
        int m;
        i = input.nextInt();
        j = input.nextInt();

        int num = 0;


        while (i != 0 || j != 0) {
            num += 1;
            e = (e + 1) % 100;
            m = (m + 1) % 400;
        }

        System.out.println(num);
    }

}

The input should be two numbers in each line, one for i and one for j.

Input:

0 0
100 300
99 399
0 200

Output should be:

C1: 0 
C2: 100
C3: 1
C4: 200

Hope this explains my problem.

Thanks in advance!


Solution

  • As @Abhishek suggested, you can use a counter variable:

    public static void doSomthing(){
        Scanner input = new Scanner(System.in);
        int linesParsed = 0;
        while (linesParsed < 8 && input.hasNextLine()) {
            // What are you using these variables for? You compute their
            //  values, but then you do not use them
            int e;
            int m;
           // Where are these variables declared? It seems weird to have
            //  instance variables be named i and j
            i = input.nextInt();
            j = input.nextInt();
    
            int num = 0;
           
            // Unless i and j are being modified concurrently somewhere
            // else in the code, this will result in an infinite loop
            while (i != 0 || j != 0) {
                num += 1;
                e = (e + 1) % 100;
                m = (m + 1) % 400;
            }
    
            System.out.println(num);
            linesParsed++;
        }
    }