【问题标题】:Print only 10 outputs per line每行仅打印 10 个输出
【发布时间】:2017-03-03 01:51:38
【问题描述】:

我有一个 Printf 格式问题。我只打印 10 个数字,然后转到下一行并再打印 10 个数字,依此类推。最终目标就像一张桌子,所有的列都排成一行并向右对齐。我也在使用 while 语句。我尝试了一些我在研究中发现的不同的东西,但没有成功。除了 Printf,我会为它使用不同的打印语句吗?比如Print,还是PrintLn?还考虑过使用 If 语句。任何帮助将不胜感激!谢谢你。

    System.out.printf("Please enter a maximun integer value: ");
    Scanner scan = new Scanner(System.in);
    double n = scan.nextDouble();

    System.out.printf("The number you entered was: %.0f \n", n); // Just to check if user input is correct

    double startNum = 0;
    double sqrt = startNum;

    System.out.printf("Squares less than %.0f are: ", n);
    while ( sqrt < n) {
        sqrt = Math.pow(startNum, 2);
        System.out.printf("%6.0f", sqrt);
        startNum ++;
    }

【问题讨论】:

  • 也许你应该记录你已经打印了多少,并在每 10 个之后开始一个新行。
  • 很明显,如果您想每行打印 10 个,您将需要跟踪您正在打印的数字,对吗?当你打印第 10 个时,你会开始一个新行并重置你的计数器,你不觉得吗?
  • @KenWhite 或 mod by 10。
  • @shmosel:是的。你仍然需要一个计数器来修改 10。
  • @KenWhite 绝对是。

标签: java format printf output


【解决方案1】:

使用MOD条件,可以保证每行10个输出。

import java.util.Scanner;

class Test {
    public static void main(String[] args) {
        System.out.printf("Please enter a maximun integer value: ");
        Scanner scan = new Scanner(System.in);
        double n = scan.nextDouble();

        System.out.printf("The number you entered was: %.0f \n", n); // Just to check if user input is correct

        double startNum = 0;
        double sqrt = startNum;

        System.out.printf("Squares less than %.0f are: ", n);
        while (sqrt < n) {
            sqrt = Math.pow(startNum, 2);
            if(startNum != 0 && startNum % 10 == 0) {
                System.out.println();
            }
            System.out.printf("%6.0f", sqrt);
            startNum++;
        }
    }
}

输出 -

请输入最大整数值:150

您输入的数字是:150

小于 150 的正方形是:0 1 4 9 16 25 36 49 64 81

121 144 169

【讨论】:

  • 感谢您的帮助!我以为您必须使用 If 语句,但我不太确定如何设置它。现在看来,很有道理。
  • 有不同的方法可以做到这一点,Mod 只是其中一种直接的选择。
  • 第一行是正确的。虽然,后面的每一行只有 9 个数字。
  • @Sig.1855,您找到根本原因了吗?尝试,只有在您给予足够的尝试后才能查看上述编辑后的答案。
【解决方案2】:
while ( sqrt < n) {
    sqrt = Math.pow(startNum, 2);
    System.out.printf("%6.0f", sqrt);
    startNum ++;

    if(startNum%10==0){
        System.out.printf("/n");
    }
}

【讨论】:

  • 这只会在第一行打印 9 个值
  • 请在答案中添加一些解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-28
  • 1970-01-01
  • 2015-01-04
  • 2014-01-23
  • 2015-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多