简体   繁体   English

使用数据类型的条件语句

[英]conditional statement using data types

Just curious is there a way to set an if statement condition that checks if value is equal to a data type.只是好奇有没有办法设置 if 语句条件来检查值是否等于数据类型。 Like if (x=int) kind of thing.就像 if (x=int) 这样的事情。

I am suppose to create a program that checks for prime numbers but i do not know how to do it other than divide the number(entered by user) by the building block number (2-9(excluding 1 because all numbers are divisible ...)) and if all of them return a float then the number is prime.我想创建一个检查素数的程序,但除了将数字(由用户输入)除以积木号(2-9(不包括 1,因为所有数字都是可整除的)之外,我不知道如何做)。 .)) 并且如果它们都返回一个浮点数,那么这个数字就是素数。

I also think this way is inefficient but again i do not have any other clue how i would do it.我也认为这种方式效率低下,但同样我没有任何其他线索我会怎么做。 So if possible some ideas would work too.所以如果可能的话,一些想法也会奏效。

This is the structure of the code:这是代码的结构:

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");
                   }

            }
    }  

You can check if the number is equal to the number rounded to the nearest integer:您可以检查数字是否等于四舍五入到最接近的整数的数字:

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");
   }

If course this doesn't really check if the number is prime or not;当然,如果这并没有真正检查数字是否为素数; it only checks whether the number is divisible by the integers 2 to 9.它只检查数字是否可以被整数 2 到 9 整除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM