java - 如何每行打印15个数字?

标签 java arrays format

我有这段代码,它工作正常,但我想对其进行格式化,以便每行打印 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,然后在 count15 并将 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/

相关文章:

java - 对一个数组进行排序,其中多个连续的索引号形成一个应该放在一起的条目

java - Spring MVC 自定义作用域 bean

java - 从 UI 读取时文件路径错误

java - 如何在 dr Java 程序中创建计数器

C - 这个函数指针声明是什么意思?

javascript - Angular/Javascript 搜索对象键数组

python - python 中与 perl $conf{svnlook} log --revision $rev $repo 中此代码行的等效项是什么

Java 格式化行以使列对齐

linux - UNIX 和 Linux 服务器中的不同日期格式

java - 在 Tomcat 中重新部署应用程序时发生内存泄漏