1

Why scanner is not taking input of another string and skepping it? I cant understand, here is my code:

import java.util.Scanner;

public class demo {

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        String name;
        String address;
        int age;

        System.out.println("Enter your name");
        name = s.nextLine();
        System.out.println("My name is :" + name);

        System.out.println("Enter your age");
        age = s.nextInt();
        System.out.println("My age is :" + age);

        System.out.println("Enter your address");
        address = s.nextLine();
        System.out.println("My address is :" + address);
    }
}

Output :

Enter your name
dk
My name is :dk
Enter your age
22
My age is :22
Enter your address
My address is :

Roshana Pitigala
  • 7,058
  • 8
  • 38
  • 66
Dhaval
  • 11
  • 1
  • Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Roshana Pitigala Jun 04 '18 at 09:33

3 Answers3

1

It is simple. You can use s.nextLine(); after the age = s.nextInt();

Scanner provides a method nextInt() to request user input and does not consume the last newline character (\n).

System.out.println("Enter your age");
age = s.nextInt();
s.nextLine(); // consumes the \n character
System.out.println("My age is :" + age);
Roshana Pitigala
  • 7,058
  • 8
  • 38
  • 66
Poorna Senani Gamage
  • 1,170
  • 1
  • 15
  • 25
0

You should close the scanner after the last system out

0

Place below statement after Statement.out.println("My age is",age);

s.nextLine();

Above statement will do flush, which will clear the cache location in order to accept new input.

an33sh
  • 934
  • 16
  • 23