我试图让Java程序每行打印一定量的空格,然后下拉以继续列表。我在用户指定的范围内找到所有素数,然后打印出范围中的素数和素数本身。每当程序找到一个不是素数的数字时,它应该打印一个 - 。到目前为止,我有:
import java.util.Scanner;
公共类PrimeNums {public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
int startingVal;
int endingVal;
int index;
int currNum = 2;
boolean prime;
int count=0;
//*** Input ***
System.out.println("Enter the Starting Number of the Range: ");
startingVal = keyboard.nextInt();
System.out.println("Enter the Ending Value of the Range: ");
endingVal = keyboard.nextInt();
//*** Checks for Parameters ***
while(startingVal>1000||startingVal%10!=0){
System.out.println("Starting Value was not evenly divisible by 10. Reenter Starting Value: ");
startingVal= keyboard.nextInt();
}
while(startingVal>=endingVal||endingVal%10!=0||endingVal>1000){
System.out.println("Ending Value was less than Starting Value or Did Not Follow Guideline. Reenter Ending Value: ");
endingVal=keyboard.nextInt();
}
//*** Stores Checked Variables ***
int range = (endingVal);
int[] primeArray = new int[10];
//*** Checks for all Prime Numbers ***
for(index=startingVal; index<range; index++){
if(index==1||index%2==0||index%3==0||index%4==0||index%5==0||index%6==0||index%7==0||index%8==0||index%9==0||index%10==0){
System.out.print("-");
}else{
count++;
System.out.print(index);
}
}
System.out.println("There are " + count + " Prime Numbers in this range.");
}
}
到目前为止,该程序找到范围内的所有素数并打印出来。但是,我需要代码以10个为一组打印出来。这样的事情: 这里的范围是:70-200。
71 - 73 - - - - - 79 - | 80
101 - 103 - - - 107 - 109 - | 110
131 - - - - - 137 - 139 - | 140
181 - - - - - - - - - | 190
191 - 193 - - - 197 - 199 - | 200
在70到200之间有27个素数
答案 0 :(得分:1)
通过索引减去起始值,您将获得循环编号,这与使用计数器时相同。一旦你知道,%sizeOfSet == 0
如果计数器可被sizeOfSet
整除(每组的输出数量,如你所指定,10),则返回true。
int sizeOfSet = 10;
if ((index-startingVal) %sizeOfSet == 0){
//prints out an empty line
System.out.printf("%n");
}
此代码应包含在if-else语句之后的for循环的末尾。