Java 算法输出到长度开始新行

Java 算法输出到长度开始新行,java,arrays,integer,string-formatting,system.out,Java,Arrays,Integer,String Formatting,System.out,我正试图将我所写的输出格式化,以显示每行一定数量的素数列表(Eratosthenes)。是否需要将它们放入数组中才能完成此操作?除了.split(“”)之外,我还没有找到一种实现他们划分的方法,它将为每个和Oracle站点的System.out.format()呈现一行参数索引以指定长度。然而,这些都需要知道角色。我用下面的文字打印它,当然这会产生一条无限长的线 for (int count = 2; count <= limit; count++) { if (!m

我正试图将我所写的输出格式化,以显示每行一定数量的素数列表(Eratosthenes)。是否需要将它们放入
数组中才能完成此操作?除了
.split(“”)之外,我还没有找到一种实现他们划分的方法
,它将为每个和Oracle站点的
System.out.format()呈现一行参数索引以指定长度。然而,这些都需要知道角色。我用下面的文字打印它,当然这会产生一条无限长的线

  for (int count = 2; count <= limit; count++) { 
        if (!match[count]) { 
            System.out.print(count + ", ");
        } 
   }

for(int count=2;count[10]
System.out.print()时的条件)
例如已经运行了10次?也许我忽略了一些东西,对
Java
来说相对较新。提前感谢您的建议或输入。

通过使用跟踪器变量,您可以跟踪已经显示了多少项,以便知道何时插入新行。在这种情况下,我选择了10项。确切的限制是flex满足你的需要

...
int num = 0;
//loop
for(int count = 2; count <= limit; count++)
{
    if(!match[count])
    {
        if (num == 10) { System.out.print("\n"); num = 0; }//alternatively, System.out.println();
        System.out.print(count + ",");
        num++;
    }
}
...
。。。
int num=0;
//环路

对于(int count=2;count,您只需创建一些int值即可

int i = 1;
…并在每次Sysout运行时增加其值

大概是这样的:

 int i = 1;
 for (int count = 2; count <= limit; count++) { 
    if (!match[count]) {
        if (i%10 == 0) 
            System.out.print(count+ "\n");
        else 
            System.out.print(count + ", ");
        i++;
    } 
}
inti=1;
对于(int count=2;count请尝试以下方法:

int idx=1;
int itemsOnEachLine=10;
for(int count = 2; count <= limit; count++)
{
    if(!match[count])
    {
        System.out.print(count+(idx%itemsOnEachLine==0?"\n":","));
        idx++;
    }
}
intidx=1;
int itemsOnEachLine=10;

对于(int count=2;count跟踪您显示了多少素数,然后只需执行
System.out.println();num=0;
这是一个很好的解决方案。谢谢。(第一行减少了1)。啊。你说得对。我看到了解决方法。按照通常的做法,简单地减少一个。这非常有效。谢谢!唯一的补充是
System.out.print(count+“,\n”);
在调用
时保留逗号。