我有这段代码,它工作正常,但我想对其进行格式化,以便每行打印 15 个数字。
我已经看到它是用 % 或 for 循环完成的,但我不知道如何在我的代码中使用它们。感谢大家的帮助!谢谢!
import java.util.*;
import java.io.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number that you want to find all the prime numbers up to it: ");
int num = sc.nextInt();
boolean[] bool = new boolean[num];
for (int i = 0; i < bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i * i); j < num; j = j + i) {
bool[j] = false;
}
}
}
System.out.println("List of prime numbers upto given number are : ");
for (int i = 2; i < bool.length; i++) {
if(bool[i]==true)
{
System.out.print(i + " ");
}
}
}
}
最佳答案
您可以在每次 bool[i]
为 true
时增加一个 count
,然后在 count
为 15
并将 count
重置回 0
。
这是您的 print
循环现在的样子:
System.out.println("List of prime numbers upto given number are : ");
int count = 0;
for (int i = 2; i< bool.length; i++) {
if(bool[i])
{
if (count == 15) {
count = 0;
System.out.println();
}
System.out.print(i + " ");
count++;
}
}
输出:
Enter the number that you want to find all the prime numbers up to it: 120
List of prime numbers upto given number are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
53 59 61 67 71 73 79 83 89 97 101 103 107 109 113
关于java - 如何每行打印15个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60099666/