如何在每行上打印15个数字?



我有这个代码,它工作正常,但我想格式化它,以便它在每行上打印 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 + " ");
}
}
}
}

您可以在每次truebool[i]时将增量设为count,然后在15count时移动到下一行,并将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 

在你正在做的事情的上下文中,最好的选择是这样的:

int count = 0;
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 + " ");
count++;
}
if(count == 15) {
System.out.println();
count = 0;
}
}

按如下方式操作:

System.out.println("List of prime numbers upto given number are : ");
for (int i = 2, j = 1; i < bool.length; i++) {
if (bool[i] == true) {
System.out.print(i + " ");
if (j % 15 == 0) {
System.out.println();
}
j++;
}
}

运行示例:

Enter the number that you want to find all the prime numbers up to it: 200
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 
127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 
199 

如有疑问,请随时发表评论。

最新更新