到目前为止,我遇到的问题和我得到的每一个响应之间的区别是,我试图让代码打印出有多少数字是质数,而不是原始数字中有多少质数。例如,如果用户输入567,我需要测试5、6和7,并告诉他们有多少是质数。
不管怎样,我试图让这个代码打印出用户输入的数字中有多少个质数位。当我运行它时,它会打印具有(一个数字)质数的数字。但我每次运行它时,它通常都会打印出错误的数字。我认为如果我只是将一些变量换成另一个变量,这将是很好的,但是我不知道我需要改变哪些变量。+edit:我非常确定每次都需要更改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;发布于 2020-01-31 19:33:34
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;
}
}发布于 2020-02-01 08:05:28
你能做一些简单的事情,比如预定义已知的质数(因为只有很少的几个):
import java.util.*;
class Example {
static Set<Integer> primeDigits = new HashSet<>(Arrays.asList(2, 3, 5, 7));
public static void main(String args[] ) throws Exception
{
Scanner kb = new Scanner(System.in);
System.out.print("Please enter a positive number: ");
int theNum = Integer.parseInt(kb.nextLine());
int counter = 0;
while (theNum > 0) {
if (primeDigits.contains(theNum % 10))
{
counter++;
}
theNum /= 10;
}
System.out.println("The number has " + counter + " prime digits.");
}
}使用
% java Example
Please enter a positive number: 2147483647
The number has 4 prime digits.
% https://stackoverflow.com/questions/59997989
复制相似问题