0

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: 
4
  • 3
    Orthogonal to your question, but consider placing all of the functionality in your cases in different methods. It would make debugging them easier, as you don't have a whole mess of code staring you in the face. Commented Nov 3, 2012 at 16:42
  • @Makoto You mean you want me to share the whole code? :P Commented Nov 3, 2012 at 16:55
  • No. How'd you come to that thought? :S Commented Nov 3, 2012 at 16:56
  • @Makoto I'm not sure.. x_x Forgive me. Commented Nov 3, 2012 at 17:08

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.