素数对齐

时间:2015-10-25 07:16:49

标签: java

我无法正确对齐此代码。我需要它以五行十行显示,整齐排列。这就是我的,请帮忙!

import java.util.Scanner;
public class PrimeNumbers {
    public static void main(String...args) { //start main method
        Scanner sc = new Scanner(System. in ); //renamed Scanner to sc
        int a = 1; // first prime number
        int b = 227; // 50th prime number
        System.out.println(" ");

        for (int i = a; i <= b; i++) //this is the primer for the prime number formula
        {
            boolean isPrime = true; //sets the statement to true
            if (isPrime) for (int j = 2; j <= i; j++) //formula to get the prime
            {
                if (i != j && i % j == 0) //formula checking prime
                isPrime = false; //sets statement to false
            }
            if (isPrime) {

                System.out.print(i + " "); //if true it prints prime number
                System.out.printf("\n "); //if false it prints a dash

            }
        }

    } //end of main method
} //end of class

1 个答案:

答案 0 :(得分:1)

您可以使用counter变量来执行此操作,一旦打印素数,您将增加该变量。如果counter%10 returns 0,则可以添加新行。

//initialize counter with 0
...
if (isPrime)
{

System.out.print(i+" ");//if true it prints prime number
counter++;
if(counter%10==0)
System.out.println();//it will add a new line
 }
...