这是打印出来的代码。当输入0时,用户程序输入的一组数字中的素数停止。变量计数器未更新,结果仍为0.如何更新计数器的值?
class Prog4 {
public static void main(String a[]){
int c=0;
//int[] array=new int[10];
int counter=0;
Scanner b=new Scanner(System.in);
System.out.println("Enter the numbers");
c=b.nextInt();
while(c!=0){
boolean y=false;
for(int j=2;j<c;j++){
if(c%j==0)
y=true;
}
if(y=false){
counter++;
//array[counter-1]=c;
}
c=b.nextInt();
}
System.out.println("No. of prime numbers entered :" + counter);
//System.out.println("The prime numbers are : ");
//for(int x:array)
//System.out.println(x);
}
}
答案 0 :(得分:0)
做到:
public class Prog4 {
public static void main(String[] args) {
int c = 0;
int[] array = new int[10];
int counter = 0;
System.out.println("Enter the numbers:");
do {
Scanner b = new Scanner(System.in);
c = b.nextInt();
boolean y = false;
for (int j = 2; j < c; j++) {
if (c % j == 0)
y = true;
}
if (y == false && c != 0) {
counter++;
array[counter - 1] = c;
}
} while (c != 0);
System.out.println("No. of prime numbers entered:" + counter);
System.out.println("The prime numbers are: ");
for (int i = 0; i < counter; i++)
System.out.println(array[i]);
}
}
输入:
Enter the numbers:
1
2
3
4
5
6
7
8
9
10
11
0
输出:
No. of prime numbers entered: 6
The prime numbers are:
1
2
3
5
7
11
基本上,这是错误的: