1

I am learning Java and I was trying an input program. When I tried to input an integer and string using instance to Scanner class , there is an error by which I can't input string. When I input string first and int after, it works fine. When I use a different object to Scanner class it also works fine. But what's the problem in this method when I try to input int first and string next using same instance to Scanner class?

import java.util.Scanner;

public class Program {
    public static void main(String[] args) {

        Scanner input=new Scanner(System.in);

        //Scanner input2=new Scanner(System.in);

        System.out.println("Enter your number :" );

        int ip = input.nextInt();

        System.out.println("Your Number is : " + ip);

        System.out.println("Enter Your Name : ");

        String name= input.nextLine();

        System.out.println("Your Next is : " + name);
    }
}
Luiggi Mendoza
  • 81,685
  • 14
  • 140
  • 306
Shubham
  • 37
  • 7

3 Answers3

4

nextInt() doesn't wait for the end of the line - it waits for the end of the token, which is any whitespace, by default. So for example, if you type in "27 Jon" on the first line with your current code, you'll get a value of 27 for ip and Jon for name.

If you actually want to consumer a complete line, you might be best off calling input.nextLine() for the number input as well, and then use Integer.parseInt to parse the line. Aside from anything else, that represents what you actually want to do - enter two lines of text, and parse the first as a number.

Personally I'm not a big fan of Scanner - it has a lot of gotchas like this. I'm sure it's fine when it's being used in exactly the way the designers intended, but it's not always easy to tell what that is.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
0

If you call input.nextInt(); the scanner reads the number from the input, but leaves the line separator there. That means, if you call input.nextLine(); next, it reads everything till the next line separator. And this is in this case only the line separator itself.

You can fix that in two ways. Way 1:

int ip = Integer.parseInt(input.nextLine());
// output
String name= input.nextLine();

Ways 2:

int ip = input.nextInt();
// output
input.nextLine();
String name= input.nextLine();
Tom
  • 14,120
  • 16
  • 41
  • 47
0

This one working, Anyway if you want to save IP address it must be String.

import java.util.Scanner;

public class Program {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        //Scanner input2=new Scanner(System.in);
        System.out.println("Enter your number :");

        int ip = input.nextInt();

        System.out.println("Your Number is : " + ip);

        System.out.println("Enter Your Name : ");

        input.nextLine();

        String name = input.nextLine();

        System.out.println("Your Next is : " + name);
    }
}
Damith Ganegoda
  • 3,122
  • 5
  • 34
  • 43