到目前为止,我遇到的问题和得到的每个答复之间的区别是,我正在尝试使代码打印出多少个质数是素数,而不是原始数中有多少个质数。例如,如果用户输入567,则我需要测试5、6和7并确定有多少是质数。
无论如何,我正在尝试使此代码打印用户输入的数字中有多少个质数位。当我运行它时,它会打印该数字具有(一个数字)质数。但通常每次我运行时都会打印错误的数字。我认为,如果仅将某些变量切换为另一个变量,那将是很好的选择,但我无法弄清楚需要更改哪些变量。+ edit:我很确定我每次都需要更改Num的值,但是我不确定如何做到这一点。我尝试将x ++更改为theNum%10,但它说x必须增加。顺便说一句,我正在执行Num%10,因为我需要分别测试Num的每个数字。
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;
}
}