Home > OS >  Last String Input (y/n) is overlooked by the Program. While loop is not breaking
Last String Input (y/n) is overlooked by the Program. While loop is not breaking

Time:04-10

Here is a basic while loop program, where the program at the end should ask the user if you want to keep going or not. The bug is that the program doesn't let me input (y/n) which is the last String Input.

This does not happen when the last input is an integer value.

import java.util.Scanner;

public class lol {
    
    public static void main(String[] args) {
        
    Scanner sc = new Scanner(System.in);

    int age;
    String name = "";
    String height = "";
    String userOption = "";

        while (!userOption.equals("n"))
        {
            
            System.out.println();
            System.out.print("Enter your name: ");
            name = sc.nextLine();
 
            System.out.println();

            System.out.print("Enter your age: ");
            age = sc.nextInt();

            System.out.println();

            System.out.print("Enter your height: ");
            height = sc.nextLine();

            System.out.println();
            
            System.out.println("Do you want to keep going? (y/n)");
               
            // The program over looks this line of code
            userOption = sc.nextLine();
            
            if(userOption.equals("y"))
            {
                System.out.println("Breaking");
                break;
            }
            else
            {
                continue;
            }
            
        }
    
    }



        
}

CodePudding user response:

See this topic, additional nextLine() call could be a workaround

Scanner is skipping nextLine() after using next() or nextFoo()?

CodePudding user response:

Minor adjustments to the code will fix its behaviour ;)

    Scanner sc = new Scanner(System.in);

    int age;
    String name = "";
    String height = "";
    String userOption = "";

    while (true) {

        System.out.print("Enter your name: ");
        name = sc.nextLine();

        System.out.println();

        System.out.print("Enter your age: ");
        age = sc.nextInt();

        System.out.println();

        System.out.print("Enter your height: ");
        height = sc.nextLine();

        System.out.println();

        System.out.println("Do you want to keep going? (y/n)");

        // The program over looks this line of code
        userOption = sc.nextLine();

        if (userOption.equals("y")) {
            // nothing
            System.out.println("Continuing");
        } else {
            System.out.println("Stopping");
            break;
        }

    }

    System.exit(0);

I would however agree that you should take a look at Scanner is skipping nextLine() after using next() or nextFoo()?

  •  Tags:  
  • java
  • Related