使用数据类型

时间:2015-07-03 01:36:18

标签: java if-statement type-conversion

很奇怪有没有办法设置if语句条件来检查value是否等于数据类型。就像if(x = int)那样。

我想创建一个程序来检查素数但我不知道怎么做除了将数字(由用户输入)除以构件块号(2-9(因为所有数字都是1) divisible ...))如果所有这些都返回一个浮点数,则数字为素数。

我也认为这种方式效率低下,但我再也没有任何其他线索如何做到这一点。所以如果可能的话,一些想法也会起作用。

这是代码的结构:

package innocence;
import java.util.*;

    class GS1
    {

            public static void main(String[]args)
             {
                Scanner input = new Scanner(System.in);  
                double num;
                System.out.println("Enter a number to check if it is prime or not");
                num=input.nextDouble();


                if((num % 2 == float) || (num % 3== float) || (num % 4 == float)|| (num % 5 == float)|| (num % 6 == float)|| (num % 7 == float)|| (num % 8 == float)|| (num % 9 == float) ) // float returns an error but i want to do it so it checks if it is a float or not
                   {
                      System.out.println("The number you haver entered," + num + "is a prime number");
                   }        

                else
                   {
                  System.out.println("The number entered is not prime");
                   }

            }
    }  

1 个答案:

答案 0 :(得分:0)

您可以检查数字是否等于舍入到最接近的整数的数字:

public static boolean isInteger(double n) {
    return n == Math.round(n);
}

if(!isInteger(num % 2) && !isInteger(num % 3) && !isInteger(num % 4) &&
   !isInteger(num % 5) && !isInteger(num % 6) && !isInteger(num % 7) &&
   !isInteger(num % 8) && !isInteger(num % 9) )
   {
      System.out.println("The number you haver entered," + num + "is a prime number");
   }        

else
   {
  System.out.println("The number entered is not prime");
   }

如果当然这并没有真正检查数字是否为素数;它只检查该数字是否可以被整数2到9整除。

相关问题