Search code examples
javaloopswhile-loopprogram-entry-pointdo-while

Java - How to end a process of a while function


I need a program that asks the user to introduce up to 10 names (to end, the user could type "fim" [that is end in Portuguese]).

My current problem is how to terminate the program if the user reach 10 names.

Here is my main function:

public static void main(String[] args) {
    Scanner keyboard = new Scanner (System.in);
    System.out.println("Introduza até 10 nomes completos com até 120 caracteres e pelo menos dois nomes com pelo menos 4 caracteres: ");
    String nome = keyboard.next();
    for(int i = 0; i < 10; i++) {
        while(!nome.equalsIgnoreCase("fim") && i<10) {
            nome = keyboard.next();
        }
    }
    keyboard.close();
}

Solution

  • You're running into an infinite loop with the while as is. You want to change it to an if statement and ask just for fim and call break; if that happens.

    So it should end as:

    for(int i = 0; i < 10; i++) { //This will run 10 times
        nome = keyboard.next();
        if(nome.equalsIgnoreCase("fim")) { //This will verify if last input was "fim"
            break; //This breaks the for-loop
        }
    }
    

    Or if you really want to use a while loop inside the for one (not recommended tho) you need to increase i inside it:

    for(int i = 0; i < 10; i++) {
        while(!nome.equalsIgnoreCase("fim") && i<10) {
            nome = keyboard.next();
            i++;
        }
    }