0

when i run the following code in java:

import java.util.*;
class Solution{
    public static void main(String []argh)
    {
        Scanner sc = new Scanner(System.in);
        try{
            long x=sc.nextLong();
            System.out.println(x);
        }
        catch(Exception e){
            System.out.println(sc.next()+" can't be fitted anywhere.");
        }
       sc.close();
   }

}

and enter the input as "23333333333333333333333333333333333333333" it gives the following output :

23333333333333333333333333333333333333333 can't be fitted anywhere.

When sc.nextLong() throws InputMismatchException then how does the sc.next() in the catch block get the exact same value entered for sc.nextLong() in try block? Should it not ask for the input from consoleenter code here?

cnova
  • 725
  • 2
  • 9
  • 22

2 Answers2

3

Maximum value of long is 9223372036854775807, your number is bigger than that. Try using BigInteger. next() takes the number as a String, so it can accept anything. Note that next() gets that value because that value is still present in the stream.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • You can also add in the answer a quick reference link to the sizes of `primitive types` - http://www.tutorialspoint.com/java/java_basic_datatypes.htm - as the answer is descriptive enough and should be accepted :) – Phantomazi Sep 18 '15 at 08:28
  • Okay. So when `nextLong()` is executed, since the value is not assigned to `x` due to the `InputMismatchException`, it remains in the Stream, waiting to be consumed? – cnova Sep 18 '15 at 08:31
  • @cnova - Yes. What you can do is read it (into a String) and then ignore it. Then ask for next input – TheLostMind Sep 18 '15 at 08:34
  • 1
    @TheLostMind - Okay. Thanks for the prompt answer :) – cnova Sep 18 '15 at 08:40
2

I believe that your question is not about data type and it's maximum value and rather about the Scanner. If so, The Scanner API mentions this:

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

The scanner can still process the available input from stream incase of InputMismatchException

Karthik R
  • 5,523
  • 2
  • 18
  • 30