0
import java.util.Scanner;
public class HelloWorld{
    public static void main(String args[]){
    Scanner dd = new Scanner(System.in);
    System.out.println("Enter name");
    String b = dd.nextLine();
    System.out.println("Enter num");
    int num = dd.nextInt();
  }
}

And

import java.util.Scanner;
public class HelloWorld{
    public static void main(String args[]){
        Scanner dd = new Scanner(System.in);
        System.out.println("Enter num");
        int num = dd.nextInt();
        System.out.println("Enter name");
        String b = dd.nextLine();
    }
}

Why the latter doesn't work peoperly(doesn't let me enter name), while the first one does?

I have made up a new version without that annoying "Scanner scan = new Scanner". And what about this solution? What cons may it have?

import java.util.Scanner;
public class HelloWorld{
public static void main(String args[]){
    System.out.println("Enter num");
    int i = new Scanner(System.in).nextInt();
    System.out.println("Enter name");
    String b = new Scanner(System.in).nextLine();
  }
}
Dima_736
  • 27
  • 7

2 Answers2

0

In the second case, nextInt() does not scan over the newline character that the user inputs when pressing the Return key.

In the first case, nextLine() is encountered first so the problem doesn't manifest itself.

The moral of the story is to always use nextLine() and parse the resulting string accordingly. Use something like Integer#parseInt to convert a string to an integer.

Bathsheba
  • 220,365
  • 33
  • 331
  • 451
0

The second program expects an Int first and then a name. And hence might be erroring out when a name is entered.

Yogesh_D
  • 14,022
  • 8
  • 31
  • 47