Lamia
Lamia

Reputation: 49

How to read string with space within loops in java?

We all know that using method input.nextLine() will allow spaces for the string while running the program, but.. When I use this method inside a loop the run skips the statement. Can anyone please explain why?

I'm trying it with menu:

Code:

do {
    System.out.print("Enter your choice: ");
    choice = input.nextInt();

    switch (choice) {

    case 4:
        System.out.println("Please give the full information of the project ");
        System.out.print("Project code: "); int code = input.nextInt();
        System.out.print("Project Title: "); String title = input.nextLine();
        System.out.print("Project Bonus in Percent: "); double bip = input.nextDouble();
        Project proj4 = new Project(code4,title4,bip4);
        System.out.print("Employee ID you're adding project to: "); String id4=input.next();
        ers.addProjectToEmployee(id4,proj4);
        break;

    /* more cases  */
    }
} while (choice !=13);

Check statement 3 in case 4.

Here's what happened while running the program:

Enter your choice: 4
Please give the full information about the project 
Project code: 66677
Project Title: Project Bonus in Percent: 

Upvotes: 0

Views: 1941

Answers (1)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

input.nextInt() does not read the end-of-line, so that' why the effect that .nextLine() is being escaped, while actually that .nextLine() is reading the end-of-line left unread in the input-stream by the .nextInt(). You need an extra .nextLine() after .nextInt().


Update:

Do the following:

System.out.print("Project code: "); int code = input.nextInt();
input.nextLine(); // this is what you need to add
System.out.print("Project Title: "); String title = input.nextLine();

Upvotes: 1

Related Questions