由于某种原因,当我测试它时,第二个if语句总是打印一个和用户输入的数字之间的每个数字,即使它是非素数。但是,第三个if语句正确表明用户的号码是否为素数。我有什么不对劲吗?
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in) ;
System.out.println("intput a number") ;
int number = input.nextInt() ;
int counter = 0 ;
int counter2 = 0 ;
for (int i = 1 ; i <= number ; i++) {
for (int j = 1 ; j <= i ; j++) {
if (i % j == 0 ) {
counter ++ ;
}
else if (i%j != 0) {
}
}
if (counter != 2) {
System.out.println( i+" is not prime") ;
}
if (counter == 2) {
System.out.println(i+", is a prime") ;
}
System.out.println("\n") ;
if (number % i == 0) {
counter2 ++ ;
}
}
if (counter2 != 2) {
System.out.println( number+" is not prime") ;
}
else if (counter2 == 2){
System.out.println( number+" is a prime") ;
}
}
答案 0 :(得分:1)
你的程序似乎有点过于复杂,为什么不只是制定一个方法来确定它是否prime
?
示例:强>
public static boolean isPrime(int number){
if(number <= 1) return false;
for (int i = 2; i < number; i++){
if (number % i == 0) return false;
}
return true;
}
在main方法中,只需调用它:
Scanner input = new Scanner(System.in) ;
System.out.println("input a number") ;
int number = input.nextInt() ;
for (int i = 1 ; i <= number ; i++) {
if(isPrime(i)){
System.out.println( i+" is a prime") ;
}else{
System.out.println( i+" is NOT a prime") ;
}
}
答案 1 :(得分:0)
您对所有数字使用相同的计数器,但您没有重置它,因此计数器的值正在上升。
int counter;
int counter2 = 0 ;
for (int i = 1 ; i <= number ; i++) {
//Resets the counter
counter = 0 ;
for (int j = 1 ; j <= i ; j++) {
if (i % j == 0 ) {
counter ++ ;
}
else if (i%j != 0) {
}
}
//You don't need two if's if one is the negation of the other
if (counter != 2) {
System.out.println( i+" is not prime") ;
}
else{
System.out.println(i+", is a prime") ;
}
System.out.println("\n") ;
if (number % i == 0) {
counter2 ++ ;
}
}
//You don't need two if's if one is the negation of the other
if (counter2 != 2) {
System.out.println( number+" is not prime") ;
}
else{
System.out.println( number+" is a prime") ;
}
如果您使用isPrime功能告诉您数字是否为素数,那么您可以避免头痛。它会看起来更清晰。