我遇到的问题和到目前为止我得到的每个回复之间的区别在于,我试图让代码打印有多少个数字是素数,而不是原始数字中有多少个素数。例如,如果用户输入 567,我需要测试 5、6 和 7,并判断有多少是素数。
无论如何 - 我试图让这段代码打印用户输入的数字中有多少个质数数字。当我运行它时,它会打印 The number has (a number) primenumbers。但每次运行时它通常都会打印错误的数字。我想如果我只是将一些变量切换为另一个变量,那就很好了,但我不知道需要更改哪些变量。
+编辑:我很确定我每次都需要更改 theNum
的值,但我不确定如何做到这一点。我尝试将 x++
更改为 theNum%10
但它说 x 必须增加。顺便说一句,我正在执行 theNum%10
因为我需要单独测试 theNum
的每个数字。
int choice = 3, theNum, copy, x, y, counter, even, odd, zero;
System.out.print("Please enter a positive number ");
theNum = Integer.parseInt(kb.nextLine());
case 3:
// using nested for loops print the prime numbers
counter = 0;
for (x = 1; x <= theNum; x++) {
for (x = 2; x <= theNum; x++) {
if (theNum % 10 % x == 0) counter++;
}
}
System.out.print("The number has " + counter + " prime numbers.");
break;
最佳答案
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner kb = new Scanner(System.in);
int theNum,counter=0,remainder;
System.out.print("Please enter a positive number ");
theNum = Integer.parseInt(kb.nextLine());
while(theNum>0) {
remainder = theNum%10;
if(isPrime(remainder))
counter++;
theNum = theNum/10;
}
System.out.print("The number has " + counter + " prime numbers.");
}
static boolean isPrime(int n)
{
if (n <= 1) return false;
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
}
关于java - 如何让这段代码打印一个数字中有多少个素数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59997989/