java - 为什么我的输入 -100000000000000 得到不正确的输出?

标签 java types long-integer

    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.

最佳答案

你的逻辑可能会变得乏味。使用 Wrapper 类方法,这样您就可以在不提供 then 范围本身的情况下工作。

例如:

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();
          }
       }

      }

希望这有帮助!

关于java - 为什么我的输入 -100000000000000 得到不正确的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57340311/

相关文章:

java - Spring 批处理 : Propagate exception encountered in partitioned step (Stop job execution)

java - 我无法将我的用户名和密码从一个 jframe 转移到另一个 jframe

java - Android,单击 ListPreference 项目时显示对话框

java - 翻转超过最大字节大小的位移位有问题吗?

haskell - 究竟是什么使类型系统保持一致?

Java:Math.pow() 返回零

oracle - 如何在没有自定义类型或游标的情况下从 Oracle 函数返回表?

oracle - 什么是 MLSLABEL Oracle 数据类型?

java - 使用 long 计算素数 (Java)

Java - 将人类可读大小转换为字节