Prerna Bhadoria
Prerna Bhadoria

Reputation: 27

Why am I getting incorrect output for input -100000000000000?

    public class dataType {

    public static  void  main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int t=sc.nextInt();

        for(int i=0;i<t;i++)
        {
            try
            {
                long x=sc.nextLong();
                System.out.println(x+" can be fitted in:");
                if(x>=-128 && x<=127)System.out.println("* byte");
                if(x>=-1*(int)(Math.pow(2,15)) && x<=(int)(Math.pow(2,15)-1))System.out.println("* short");
                if(x>=-1*(int)(Math.pow(2,31)) && x<=(int)(Math.pow(2,31)-1))System.out.println("* int");
                if((x>=-1*(int)(Math.pow(2,63))) &&( x<=(int)(Math.pow(2,63)-1)))
                    System.out.println("* long");


            }
            catch(Exception e)
            {
                System.out.println(sc.next()+" can't be fitted anywhere.");
                sc.next();
            }

        }
    }
}

For the Input number= -100000000000000, Expected Output = -100000000000000 can be fitted in: * long Actual Output = -100000000000000 can be fitted in:

Problem is that it is not printing the message after the last if condition to check whether the number is in range of long data type.

Upvotes: 0

Views: 115

Answers (3)

Aadit S. Bagga
Aadit S. Bagga

Reputation: 65

sir actually there was no need for (int)Math.pow(2,63) because it would cause a overflow

Upvotes: 0

robot13
robot13

Reputation: 71

I believe the line where you have (int)(Math.pow(2,63) results in overflow? You'd have to store that in a larger datatype such as a long

Upvotes: 1

abhivemp
abhivemp

Reputation: 932

Your logic can get tedious. Use the Wrapper class methods so you could work without providing then ranges themselves.

For instance:

Scanner sc = new Scanner(System.in);
      int t = sc.nextInt();
      int x = 0;
      for(int i = 0; i <=t;i++) {
          x = sc.nextInt();
          try  {
            if(x >= BYTE.MINVALUE && x <= BYTE.MAXVALUE) System.out.println("Byte");
           //Same format for all required datatypes

          }
          catch(Exception e)  {
              System.out.println(sc.next()+" can't be fitted anywhere.");
              sc.next();
          }
       }

      }

Hope this helps!

Upvotes: 1

Related Questions