-1

I'm trying to get the character and string from the user.But it gets only character and doesn't get the string.

    Scanner in=new Scanner(System.in);
    String s;
    System.out.println("Enter a string");
    char c = in.next().charAt(0); 
    System.out.println(c);
    s = in.nextLine();
    System.out.println(s);
gayathri
  • 49
  • 4
  • Possible duplicate of [How can I get the user input in Java?](https://stackoverflow.com/questions/5287538/how-can-i-get-the-user-input-in-java) – GJCode May 29 '19 at 17:12
  • Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – GBlodgett May 29 '19 at 17:14
  • This seems to be a duplicated question . It would be better if you can clearly highlight whether you want to get a particular character from the taken string or not . It's a good practice to highlight the difference of your question from existing questions to consider it as a new question. – Lahiru Wijesekara Jun 25 '19 at 08:15

2 Answers2

0

When you call next() with the scanner, you are getting the entire string until the next complete token. The next time you call nextLine(), the string you were after is gone. Assuming the character you want is at the start of the string, you should get the string, and then get the character from the string.

s = in.nextLine();

char c = s.charAt(0);
Nordii
  • 456
  • 1
  • 3
  • 14
0

Try with this:

    public static void main(String args[]) // start of main
     {
      Scanner in=new Scanner(System.in);
      String s;
      System.out.println("Enter a char");
      char c = in.next().charAt(0);
      System.out.println(c);
      System.out.println("Enter the String");
      s = in.next();
      System.out.println(s);
   }
AmitD
  • 84
  • 6