0

我正在尝试让 Java 程序每行打印特定数量的空格,然后下拉以继续列表。我正在查找用户指定范围内的所有素数,然后打印出该范围内的素数和素数本身。每当程序发现一个不是素数的数字时,它应该打印一个 - 。到目前为止,我有:

导入 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

    • 83 - - - - - 89 - | 90
            • 97 - - - | 100

101 - 103 - - - 107 - 109 - | 110

    • 113 - - - - - - - | 120
            • 127 - - - | 130

131 - - - - - 137 - 139 - | 140

                • 149 - | 150
151 - - - - - 157 - - - | 160

    • 163 - - - 167 - - - | 170
    • 173 - - - - - 179 - | 180

181 - - - - - - - - - | 190

191 - 193 - - - 197 - 199 - | 200


70到200之间有27个质数

4

1 回答 1

1

通过用 index 减去起始值,您将获得循环编号,这与您使用计数器时相同。一旦知道这一点,如果计数器可被(如您指定的每组输出的数量,10)%sizeOfSet == 0整除,则将返回 true 。sizeOfSet

int sizeOfSet = 10;
if ((index-startingVal) %sizeOfSet == 0){
//prints out an empty line
System.out.printf("%n");
}

此代码应包含在 if-else 语句之后的 for 循环末尾。

于 2013-04-16T00:39:28.397 回答