0
import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=1;i<=t;i++)
        {
            try
            {
                long n=sc.nextLong();
                if((n>=(-128))&&(n<=127))
                System.out.println(n+" can be fitted in:\n* byte\n* short\n* int\n* long");
                else if(n>=(-32768)&&n<=32767)
                System.out.println(n+" can be fitted in:\n* short\n* int\n* long");
                else if(n>=(-Math.pow(2,31))&&n<=(Math.pow(2,31)-1))
                System.out.println(n+" can be fitted in:\n* int\n* long");
                else if(n>=(-Math.pow(2,63))&&n<=(Math.pow(2,63)-1))
                System.out.println(n+" can be fitted in:\n* long");
            }
            catch(Exception obj)
            {
                System.out.println(sc.next()+" can't be fitted anywhere.");
            }
        }
    }
}

Why sc.next() is used in the catch block System.out.println line of code?

azro
  • 53,056
  • 7
  • 34
  • 70

1 Answers1

0

In here sc.next(), The next() method in java is present in the Scanner class and is used to get the input from the user. This method can read the input only until a space(” “) is encountered. In other words, it finds and returns the next complete token from the scanner.

if we think we didn't use this sc.next() and just only the System.out.println(" can't be fitted anywhere."); what happen is when the exception is catch it will print the output until one of your if block stratifies. As an example lets input 4lk number with string it will output

 can't be fitted anywhere.
 can't be fitted anywhere.
 can't be fitted anywhere.

three times, but using the sc.next() we can avoid that because it will look for another input.