0

I am facing problem in the following code please have a look on it and help me solve my problem. The Code is :

import java.util.*;
public class Test1{
    public static void main(String ...args){
    Scanner s1=new Scanner(System.in);
    int age;
    age= s1.nextInt();
    System.out.println(age);
    System.out.println("Enter Name");
    String name;
    s1.next();
    name = s1.nextLine();
    System.out.println(name);
}
}

Input of the Program:

12
12
Enter Name
A B C
 B C

Expected Output:

    12
    12
    Enter Name
    A B C
    A B C

I was trying the Scanner class.Please Help me to Get my Expected Output, and specify my mistake.Please explain you answer Thank you so much.

azro
  • 35,213
  • 7
  • 25
  • 55
  • 4
    `s1.next();` will discard the first token . – Arnaud Sep 25 '17 at 08:31
  • @Berger if I remove s1.next(); then this is the output 12 12 Enter Name Program got terminated without Inputing Name – Akshay Chauhan Sep 25 '17 at 08:33
  • Possible duplicate of [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – AxelH Sep 25 '17 at 08:43

1 Answers1

1
import java.util.*;

public class Test1
{
    public static void main(String ...args){
    Scanner s1=new Scanner(System.in);
    int age;
    age= s1.nextInt();
    System.out.println(age);
    System.out.println("Enter Name");
    s1.nextLine();
    String name = s1.nextLine();
   System.out.println(name);
   }
}

This should work.

sc.next() uses <space> as a delimiter by default.