0

I enter:

  • Joe Smith (press enter)
  • IT engineer (press enter)
  • Y (press enter)

What happens then, is that the loop occurs again but you cant enter your first and last name a second time.

String name = s.nextLine(); Always seems to be an empty line after the loop executes once.

Why is that?

Code:

Scanner s = new Scanner(System.in);

do {
    System.out.printl('Enter your first and last name:');
    String name = s.nextLine();

    System.out.printl('Enter your job description:');
    String job = s.nextLine();

    System.out.println("Press Y for loop ..");
    char answer = s.next().charAt(0);
} while(answer == 'Y');
bobbyrne01
  • 5,464
  • 13
  • 60
  • 127

1 Answers1

2

System.out.printl() should be System.out.println()

You should use double quotes for Strings.

 System.out.printl('Enter your first and last name:');//<----single quote

Variable answer is out of scope as In java the scope is restricted to {}. Declare answer before the do-while loop(at the top).

Instead of using char answer = s.next().charAt(0);, use answer = s.nextLine().charAt(0);

For more information please check Scanner is skipping nextLine() after using next() or nextFoo()?

Here is your modified code:

    public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    char answer; //<----declare the variable here 

do {
    System.out.println("Enter your first and last name:"); //<---use double quotes
    String name = s.nextLine();

    System.out.println("Enter your job description:");//<---use double quotes
    String job = s.nextLine();

    System.out.println("Press Y for loop ..");
    answer = s.nextLine().charAt(0); //<---use nextLine() here 
}while(answer == 'Y');
}
suvojit_007
  • 1,649
  • 2
  • 12
  • 21