限制每行输出

limit outputs per line

我正在编写一个代码,用于查找并打印用户指定值之间的每个数字,只要这些数字可以被 5 和 6 整除,但不能同时被两者整除。代码的要求之一是每行只有 10 个输出,这就是我遇到问题的部分:

 import java.util.Scanner;
 public class DivisibleBy5And6
{
  public static void main (String [] args)
 { 
   Scanner scan = new Scanner (System.in);

   final int PER_LINE = 10;

   int value = 0;

   int count = 0;

   int max = 0;

   String end = ";

   do
  { 
     System.out.print ("\nEnter a minimum number: ");
     value = scan.nextInt();

     System.out.print ("Enter a maximum number: ");
     max = scan.nextInt();

     System.out.print ("\n"); 

        while (value <= max)
        {     
           if ((value % 5) < 1 ^ (value % 6) < 1)
              System.out.print (value + " ");

           value++;

           count++;

           if (count % PER_LINE == 0)
              System.out.println();     
        }

     max = 0;

     count = 0;

     System.out.print ("\n");

     System.out.print ("\nContinue? <y/n> ");
     end = scan.next();

  }while (!end.equalsIgnoreCase("n"));


  } 
}

我搞砸了关于如何限制输出的示例,我已经看到 'count' if 语句有效并且我知道它为什么有效,但是关于计算的一些事情'value' if 语句使输出看起来与预期的不一样。如果有人知道我遗漏了什么,我将不胜感激。

计算每行的数字必须与打印一起完成,而不是每个调查的数字。

 while (value <= max)
    {     
       if ((value % 5) < 1 ^ (value % 6) < 1){
          System.out.print (value + " ");
          count++;
          if (count % PER_LINE == 0)
              System.out.println();     
       }
       value++;
    }

您应该只在实际打印内容时更新 count。将您的 if 语句更改为如下内容:

    while (value <= max)
    {     
        if ((value % 5) < 1 ^ (value % 6) < 1){
            System.out.print (value + " ");
            count++;  //update since we printed something
            if (count % PER_LINE == 0)  //check if we have printed 10 items
                System.out.println();    
        }
        value++;
    }

此外,您还应该将 System.out.println() 移到 if 中,这样您只在打印 10 个数字后才转到下一行。