0

Below is the code :

import java.util.Scanner;
public class Calculate{
  public static void main(String args[])
  {
    int age=0;
    String name="";
    Scanner scan=new Scanner(System.in);

    System.out.println("Please Enter value of your age : ");
    age=scan.nextInt();

    System.out.println("Please Enter value of your name : ");
    name=scan.nextLine();

    System.out.println("Age : "+age+", Name : "+name);
  }
}

Now, Here the issue is taking String value from the user.

I can take two INTEGER values from user one by one after pressing [ENTER]. But, In case of taking STRING value from the user Second time, It just let me out after I enter value for Age variable.

If I first take the input for String and then INTERGER than it working fine as below : (First name and then age) :

    System.out.println("Please Enter value of your name : ");
    name=scan.nextLine();

    System.out.println("Please Enter value of your age : ");
    age=scan.nextInt();

What might be the issue ?

Istiaque Hossain
  • 1,596
  • 1
  • 11
  • 22
Jaimin Modi
  • 980
  • 1
  • 12
  • 39

2 Answers2

1

The problem occurs as you hit the enter key, which is a newline \n character.

to add an additional scan.nextLine() after you read the int

System.out.println("Please Enter value of your age : ");
age=scan.nextInt();
scan.nextLine();// additional  line
Istiaque Hossain
  • 1,596
  • 1
  • 11
  • 22
1

The problem is with the scan.nextInt() method. It only reads the int value. So when you continue reading with scan.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine()

Try this:

import java.util.Scanner;
public class Main{
  public static void main(String args[])
  {
    int age=0;
    String name="";
    Scanner scan=new Scanner(System.in);

    System.out.println("Please Enter value of your age : ");
    age=scan.nextInt();

    scan.nextLine(); // This line you have to add (It consumes the \n character)


    System.out.println("Please Enter value of your name : ");
    name=scan.nextLine();

    System.out.println("Age : "+age+", Name : "+name);
  }
}

Output

Please Enter value of your age :
20
Please Enter value of your name :
ABC
Age : 20, Name : ABC
GOVIND DIXIT
  • 1,559
  • 7
  • 21