0

i am new to java and i want to take an input as follows:

0 2 a

I am able to take the integer input but unable to take the character input.

i am using following code

Scanner s = new Scanner(System.in);
int o = s.nextInt();
    if(o==0)
        {
             int l=s.nextInt();
             char c=s.next().charAt(0);
        }
4
  • does next.char(0) only take 1st letter from the input? Commented Jul 12, 2015 at 17:58
  • 1
    I don't see anything wrong in your code. Can you explain your problem a bit more. Commented Jul 12, 2015 at 18:01
  • 2
    Your code works perfectly fine (demo). Commented Jul 12, 2015 at 18:01
  • Just dump the Scanner and save yourself headaches. Commented Jul 12, 2015 at 18:15

1 Answer 1

1

May be Thats because the Scanner#nextInt method does not read the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine.

Fire a new Line after nextInt.

    Scanner s = new Scanner(System.in);
    int o = s.nextInt();
    s.nextLine();
        if(o==0)
            {
                 int l=s.nextInt();
s.nextLine();
                 char c=s.next().charAt(0);
            }
Sign up to request clarification or add additional context in comments.

1 Comment

-1. The next call to nextInt will ignore any upcoming line breaks. There is no call to nextLine in the code. Mixing nextLine and next or nextInt is generally not a good idea exactly because of these ignored nextLine statements you have to use, but if you stick to one or the other, you should not have any problems, and these aren't necessary. A comment on the question links to the code in the question working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.