Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

How does this program actually work...?

import java.util.Scanner;

class string
{
    public static void main(String a[]){
        int a;
        String s;
        Scanner scan = new Scanner(System.in);

        System.out.println("enter a no");
        a = scan.nextInt();
        System.out.println("no is ="+a);

        System.out.println("enter a string");
        s = scan.nextLine();
        System.out.println("string is="+s);
    }
}

The output is:

enter the no
1234
no is 1234
enter a string
string is=         //why is it not allowing me to enter a string here?
like image 796
user1646373 Avatar asked Sep 04 '12 14:09

user1646373


1 Answers

.nextInt() gets the next int, but doesn't read the new line character. This means that when you ask it to read the "next line", you read til the end of the new line character from the first time.

You can insert another .nextLine() after you get the int to fix this. Or (I prefer this way), read the int in as a string, and parse it to an int.

like image 200
NominSim Avatar answered Nov 06 '22 17:11

NominSim