1

I've used the Scanner var = input.nextLine(); It works for my name variable but not address? Here is my code:

Scanner input = new Scanner(System.in);

System.out.println("What is your name?");
String name = input.nextLine();

System.out.println("How old are you?");
int age = input.nextInt();

System.out.println("Where do you live?");
String address = input.nextLine();

System.out.println("Your name is " + name + ".\n You are " + age + " years old." + "\n You live at " + address + ".");

And here's what it's displaying:

What is your name?
Yassine assim
How old are you?
17
Where do you live?
Your name is Yassine assim.
 You are 17 years old.
 You live at .
azro
  • 35,213
  • 7
  • 25
  • 55
Yassine
  • 11
  • 2
  • it is answered completely at:
    https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo
    Duplicate question !!!
    – Gholamali-Irani Nov 18 '17 at 22:30

1 Answers1

2

int age = input.nextInt(); consumes the int you typed but that's it, you surely return to line after if BUT this char (return line) has not been consumed

And so input.nextLine(); of adress will do it directly


2 options :

  1. int age = Integer.parseInt(input.nextLine()); take all line and convert to int
  2. int age = input.nextInt(); input.nextLine(); take int and use, then consume return like
azro
  • 35,213
  • 7
  • 25
  • 55