2014-12-29 86 views
1

我是新来的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]); 
+1

如果(NUM ==(INT)NUM) { // Number是整数 } –

+0

何处以及如何'values'定义? –

+0

可能的重复[如何检查一个值的类型是Integer?](http:// stackoverflow。com/questions/12558206/how-can-i-check-if-a-value-is-of-type-in​​teger) –

回答

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,那么结果就不会是整数。

0
if(value == (int) value) 

或长(64位整数)

if(value == (long) value) 

,或者可以通过浮法而不的精度

if(value == (float) value) 

损失如果字符串值安全地表示正在通过,使用Integer.parseInt(value);如果传入的输入是正确的整数,它将返回一个整数。

0

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

if(num instanceof Integer) 
    System.out.println("Number is an integer"); 
1

如果输入值可以是比其他整数数字形式,由

if (x == (int)x){ 
    // Number is integer 
} 

如果字符串值被传递检查,使用的Integer.parseInt(string_var)。

1

另一种方式:

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

例如2.34f % 1将是0.34,但2f % 1 is 0.0

2

以下将不会发生,因为values数组的类型为基本int。因为这样的检查,如果values[2]是一个int是事实。 values[]always包含一个int并尝试将元素添加到不是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] 
相关问题