如何找出System.out.print的类型

问题描述

让我这样设置一些变量:

   byte a = 2;
   short b = 1;
   int c = 30;
   long d = 5;
   char e = 'E'; 
   float f = 2.21f;
   double g = 34.12;
   boolean h  = false;

我想找出以下计算的值:

(short)(g + a) != g == true || h && ! ( d % b >0) && d * f == e

所以我会选择:

System.out.println((short)(g + a) != g == true || h && ! ( d % b >0) && d * f == e;

这将返回 true 。我知道这很可能是布尔值。假设我要确定并有一个命令来打印两者和结果类型,我该怎么做?我希望它是可以一遍又一遍地复制的解决方案。

解决方法

System.out.println()非常重载。您可以使用自己的方法执行相同的操作。

static void printValueAndType(int i) {
    System.out.println("" + i + " int");
}

static void printValueAndType(boolean b) {
    System.out.println("" + b + " boolean");
}

static void printValueAndType(Object obj) {
    System.out.println("" + obj + ' ' + obj.getClass().getName());
}

总共有8种原始类型:布尔值,字节,短型,字符,整数,长型,浮点型和双精度型(您已经在问题的代码中提到了全部)。您可能会想要每个方法。

让我们尝试一下,为什么不呢?

    printValueAndType((short)(g + a) != g == true || h && ! ( d % b >0) && d * f == e);

输出:

真正的布尔值