如何检查变量是否为整数

时间:2014-12-29 06:19:34

标签: java loops while-loop logic division

我是Java新手编程的新手,我正在尝试学习绳索。我遇到了一个问题,问题源于我无法检查变量是否为整数。

int[] values = new int[3];
private Random rand = new Random();
num1 = rand.nextInt(70);
num2 = rand.nextInt(70);
num3 = rand.nextInt(70);

values[1] = num1 + num2

//we are dividing values[1] by num3 in order to produce an integer solution. For example (4 + 3) / 2 will render an integer answer, but (4 + 3) / 15 will not. 
//The (correct) answer is values[2]

values[2] = values[1]/num3

if (num3 > values[1]) {
     //This is done to ensure that we are able to divide by the number to get a solution (although this would break if values[1] was 1).
     num3 = 2
     while (values[2] does not contain an integer value) {
         increase num3 by 1
        work out new value of values[2]
        }    
} else {
    while (values[2] does not contain an integer value) {
         increase num3 by 1
        work out new value of values[2] <--- I'm not sure if this step is necessary
    }
}

System.out.println(values[2]);

6 个答案:

答案 0 :(得分:2)

另一种方式:

if(value%1 == 0){
  //True if Integer
}

E.g。 2.34f % 1将为0.34,但2f % 1 is 0.0

答案 1 :(得分:2)

以下情况永远不会发生,因为values数组的类型为primitive int。因此,检查values[2]是否为int是在事后。 values[]always包含一个int,并且尝试向value数组添加一个非int类型的元素将导致抛出 ArrayStoreException

  

如果所分配的值的类型与组件类型不是赋值兼容(第5.2节),则抛出ArrayStoreException。

// All three are of type int
num1 = rand.nextInt(70);
num2 = rand.nextInt(70);
num3 = rand.nextInt(70);

// Not possible... 
while (values[2] does not contain an integer value) {

初始化数值数组时,它将自动默认值为0

int[] values = new int[3]
System.out.println( Arrays.toString(values) );
> [0,0,0]

答案 2 :(得分:1)

如果将整数除以另一个整数,则总是有一个整数。

您需要模数(余数)操作

int num1 = 15;
int num2 = 16;
int num3 = 5;

System.out.println("num1/num3 = "+num1/num3);
System.out.println("num2/num3 = "+num2/num3);
System.out.println("num1%num3 = "+num1%num3);
System.out.println("num2%num3 = "+num2%num3);

如果模数不为0,那么结果将不是整数。

答案 3 :(得分:1)

如果输入值可以是整数以外的数字形式,请按

进行检查
if (x == (int)x){
   // Number is integer
}

如果传递了字符串值,请使用Integer.parseInt(string_var)。

答案 4 :(得分:0)

if(value == (int) value)

或长(64位整数)

if(value == (long) value)

或者可以安全地用浮点表示而不会损失精度

if(value == (float) value)

如果传递了字符串值,请使用Integer.parseInt(value);如果传递的输入是正确的整数,它将返回一个整数。

答案 5 :(得分:0)

您可以使用instanceof运算符来检查给定对象是否为整数。

if(num instanceof Integer)
    System.out.println("Number is an integer");
相关问题