2014-12-29 88 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] 
相關問題