【问题标题】:Create a table and put data inside创建一个表并将数据放入其中
【发布时间】:2020-11-17 13:49:21
【问题描述】:

如何为这段代码创建表格?

表格将显示 n 和结果。

看起来像的东西

我知道我可以使用 System.out.print(.....) 打印它,但有更好的方法吗?

      fib(n)   result
        9        34
        10       55
        11       89
      
class fib
{
    static int fib(int n)
    {
        int f[] = new int[n+2]; 
        int i;

    
        f[0] = 0;
        f[1] = 1;

        for (i = 2; i <= n; i++)
        {
            f[i] = f[i-1] + f[i-2];
        }

        return f[n];
    }

    public static void main (String args[])
    {
        int a = 9;
        int b = 10;
        int c = 11;
        System.out.println(fib(a));
        System.out.println(fib(b));
        System.out.println(fib(c));


    }
} 

【问题讨论】:

标签: java function printing output


【解决方案1】:

现在您的代码只输出fib 方法的结果。 println 方法输出您指定的数据作为参数,然后结束该行。

除了printlnPrintStream 类还有很多方法可以让你通过输出文本来做特定的事情。您可以使用的一种方法是print,它与println 的作用相同,但不会结束该行。这意味着您可以:

System.out.print("\t"); // Print a tab character
System.out.print(a); // Print variable a
System.out.print("\t"); // Print another tab character
System.out.println(fib(a)); // Calculate fib(a), print the result, and end the line

另一个有趣的方法是printf,它允许您指定一个“格式字符串”,然后用传递给该方法的附加参数的值填充它。

System.out.printf("\t%d\t%d%n", a, fib(a)); // Output the variable a and result of fib(a), and end the line

Format Strings are a pretty broad subject,但上面的示例指定应该打印两个选项卡,在第一个选项卡之后使用小数点 (%d),在第二个选项卡之后使用另一个小数点 (第二个 %d)。下一个参数(a)替换第一个小数,第二个参数(fib(a) 的结果)替换第二个小数。 %n 表示“结束行”。

同样可以输出header。

【讨论】:

  • 如果数字比制表符“大”,则无法处理。我找到的副本有很多更好的答案
  • 正确,但鉴于这个问题显然是一个家庭作业问题,我选择给出一个更简单的答案,以免用高级格式化字符串压倒海报。
  • 好吧,即使这是一个家庭作业问题,我也不喜欢“我不会研究,给我代码”的家伙 :) 我在谷歌中输入了“java println table”,现在我知道他正在寻找 System.out.format。这对我来说意味着他没有花任何时间在这个作业上
猜你喜欢
  • 2023-03-05
  • 2018-11-05
  • 2013-03-03
  • 2018-04-29
  • 2020-02-09
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多