Java loop not working because of wrong scanner usage

Java loop not working because of wrong scanner usage

Problem Description:

I’m making a text editor in java.
I’m using a switch to create a menu.
One of the options of the menu is to insert lines to the existing array where i need to make a loop to add strings to an array and make it stop when i add a empty string.
Note: i cannot use array lists.
i can only use this array.

int tamMax=100;
String [] linhas = new String[tamMax];

This is the code i have so far

        System.out.println("(I)nserir linhas no fim (termine com uma linha vazia");
        System.out.println("(L)istar linhas");
        System.out.println("(A)pagar última linha");
        System.out.println("(E)ditar");
        System.out.println("(F)erramentas");
        System.out.println("(S)air");
        menuPrincipal = input.next().charAt(0);
        switch(menuPrincipal) {
            case 'i':
            case 'I':
                int i=0;
                while (true) {  
                    linhas[i] = input.nextLine();
                    System.out.println(linhas[i]);
                    if (linhas[i].isEmpty()) {
                        break;
                    }
                    i++;
                }
                System.out.print(Arrays.toString(linhas));

The loop itself is working fine, the problem is when i put the loop inside the switch case, once i do that and i press "i" the loop stops working, it doesn’t let me type anything and only outputs the following result:[, null, null, null, null, null, null, null …

Solution – 1

linhas[i] will always be null. You want to check the string that was inserted in the previous iteration (i - 1).

You can do the check within the for-loop body.

for (int i = 0; ; i++) {
    linhas[i] = input.nextLine();
    System.out.println(linhas[i]);
    
    if (linhas[i].isEmpty()) {
        break;
    }
}

If you don’t want the empty string to be inserted, move the check before assignment.

String element = input.nextLine();
System.out.println(element);
if (element.isEmpty()) {
    break;
}
linhas[i] = element;
i++;

Since you do not know the number of times the loop will run, a while loop may be preferred.

while (true) {
    linhas[i] = input.nextLine();
    System.out.println(linhas[i]);
    if (linhas[i].isEmpty()) {
        break;
    }
    i++;
}
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject