【问题标题】:Changing the value of a printed variable in a table更改表中打印变量的值
【发布时间】:2018-03-11 23:34:38
【问题描述】:

我有一个使用循环创建乘法表的任务,第一列应该从 1-10 开始,左上角有一个“x”。这是我的程序:

public class s {

    public static void main(String[] args) {
        int a = 10;
        for (int b = 0; b <= a; b++) {
            for (int c = 1; c <= 1; c++) {
                System.out.printf ("%3d | ", + b*c );
            }
        }
        System.out.println ();
        for (int d = 5; d < a; d++) {
            System.out.printf ("-------------");
        }
        System.out.println ("");
        for (int e = 1; e <= a; e++) {
            for (int c = 0; c <= a; c++) {
                System.out.printf ("%3d | ", e*c );
            }
            System.out.println ();
        }
    }
}

这会在第一列打印全零,但我希望它变为 x、1、2、3 等。如何更改这些值?

抱歉,如果有任何格式错误或任何问题,我对 Stack Overflow 和 Java 一样陌生,但我很高兴找到你。

【问题讨论】:

  • 与其为“格式错误”道歉,不如发布格式良好的代码。
  • 告诉我我做错了什么,我会从中吸取教训。如果我知道任何错误,我会在发布之前修复它们。这只是没有建设性的。
  • 你的代码都是左对齐的——你的代码在现实生活中是这样的吗?你的导师有没有教你如何缩进 Java 代码?这不仅仅是为了创建漂亮的代码,而是为了创建更易于理解和调试的可读代码。请解决这个问题。这将对您和我们都有帮助,因为如果我们能够阅读和理解您的代码,我们就能更好地了解您可能遇到的问题。
  • 这次我已经为您格式化了您的代码,但同样,请在您以后的问题中自己执行此操作。
  • 我很感激,我会的。

标签: java loops tabular


【解决方案1】:

您的代码已经非常接近工作了。您遇到的唯一问题是尝试将左列包含在 for 循环中(专用于打印乘法值)。一般形式应该是:

System.out.printf(... left hand label ...);
for (col counter ...)
   System.out.printf(... value based on col ... );
System.out.println();

调整后的代码为:

public class s {
    public static void main(String[] args) {
        int a = 10;
        System.out.printf("%3s | ", "x");
        for (int b = 1; b <= a; b++) {
            System.out.printf("%3d | ", b);
        }
        System.out.println();
        System.out.printf("----+");
        for (int d = 0; d < a; d++) {
            System.out.printf("-----+");
        }
        System.out.println();
        for (int e = 1; e <= a; e++) {
            System.out.printf("%3d | ", e);
            for (int c = 1; c <= a; c++) {
                System.out.printf("%3d | ", e * c);
            }
            System.out.println();
        }
    }
}

我还鼓励您使用以大写字母开头的类名(按照惯例,类名应大写)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多