Search code examples
javaloopsio

How to implement an input in a loop


I wanted to create a loop where I can input my name using a Scanner, but the system keeps spamming "Gimme your name" and doesn't leave me the chance to input my name. I want the system to output "Gimme your name" and wait for my input.

Scanner sc = new Scanner(System.in);
char reponse = 'O';
name = sc.nextLine();
while (reponse=='O')

    System.out.println("Gimme your name! ");
    name = sc.nextLine();
    System.out.println("Hello "+name+"How are you doing ? \n Wanna retry ? (O/N)" );
    reponse = sc.nextLine().charAt(0);

Solution

  • Try putting open close brackets around the while statement:

       char reponse = 'O';
        name = sc.nextLine();
        while (reponse=='O') {
    
            System.out.println("Gimme your name! ");
            name = sc.nextLine();
            System.out.println("Hello "+name+"How are you doing ? \n Wanna retry ? (O/N)" );
            reponse = sc.nextLine().charAt(0); ``` 
    
        }