1

I'm new to java and I wrote this code

import java.util.Scanner;

public class GamingJava {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String Name;
        int password;
        String yEs;

        System.out.print("hello sir what is your name? ");
        Name = input.nextLine();
        System.out.print("what is your password? ");
        password = input.nextInt();
        System.out.println("your name was "+Name+" and your password was "+password);
        System.out.print("are you sure? ");
        yEs = input.nextLine();
        System.out.println(yEs);
    }
}

It only ask the name and the password, but Java doesn't ask the last one how did that happen?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Anto gamus
  • 13
  • 2

1 Answers1

0

It asks for the input and immediately takes it as an empty string i.e. "".

Root Cause : The issue is because of the nextLine() method. Since while providing an input, user has to press the Enter key, the cursor/prompt on the console moves to next line. This line is taken as an empty line by the nextLine() method.

Solution : You must use the next() method as it looks out for the presence of space character for taking the input.

FYR the following line of code

yEs = input.nextLine();

should be changed to

yEs = input.next();
Sharad Nanda
  • 406
  • 1
  • 15
  • 27
  • Glad to help! You can mark it as right answer through the tick as it will benefit the community to get to the right question and answer while searching their problem. :) – Sharad Nanda Oct 31 '21 at 06:40
  • but what if I wan't to ask the int again? do I need to put next(); to or what? – Anto gamus Oct 31 '21 at 06:41
  • You will have to use the nextInt() method for that. – Sharad Nanda Oct 31 '21 at 06:42
  • I suggest you use boolean for this "yEs" variable because it will have either true or false value. That will reflect good choice with respect to data structure. – Sharad Nanda Oct 31 '21 at 06:43