有关使这些列排队(Java)的任何想法?

时间:2013-03-12 04:11:07

标签: java for-loop

我正在练习用Java编写循环。这就是我到目前为止所做的:

    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;
System.out.println ("Num  "+"Square  "+"Num  "+"Square  "+"Num  "+"Square  "+"Num  "+"Square  ");
    for (int x = 1; x<=20; x++) {
                a = x * 1;
                b = 20+a;
                c = 40+a;
                d = 60+a;
               for (int y = 1; y <= 1; y++) {
System.out.println (a + "     " + (a * a) + "      " + b + "   " + (b * b) + "      " + c +
             "     " + (c * c) + "      " + d + "     " + (d * d));
              }

         }

我根本不想更改代码(这意味着我不想添加比现有更复杂的东西),但我希望列排成一行。当数字开始以数字递增时,显然间距变得混乱。有想法该怎么解决这个吗?

编辑:为了回答你的问题,我对此很陌生,并没有比这更多地教自己。我更确定有更好的方法来做到这一点,但我只是练习我的for循环。 Anywho,谢谢你的帮助。

4 个答案:

答案 0 :(得分:1)

您可以使用标签(\t)对其进行格式化。双选项卡将为您提供更多空间。

// Changed Num to Number - Out of habit
System.out.println("Number\t\t" + "Square\t\t" + "Number\t\t" + "Square\t\t" + "Number\t\t" + "Square\t\t" + "Number\t\t" + "Square");

System.out.println(a + "\t\t" + (a * a) + "\t\t" + b + "\t\t" + (b * b) + "\t\t" + c + "\t\t" + (c * c) + "\t\t" + d + "\t\t" + (d * d));

答案 1 :(得分:1)

public String appendBlankSpace(int val){
String returnValue=Integer.toString(val);
int lengthTobeAppend=10-returnValue.length();
//Here you can use any number instead of 10.It is for space allocated for a column

for(int i=1;i<=lengthTobeAppend;i++){
returnValue= " " + returnValue;
}

return returnValue;
}

现在你可以使用,

System.out.println (appendBlankSpace(a) + appendBlankSpace(a * a) +       appendBlankSpace(b) + appendBlankSpace(b * b) +  appendBlankSpace(c) + appendBlankSpace(c *     c) + appendBlankSpace(d) + appendBlankSpace(d * d));

我希望它会对你有所帮助。

答案 2 :(得分:0)

你可以在数组中存储a,b,c,d值,如内循环

 for (int x = 1; x<=20; x++) {
                a = x * 1;
                b = 20+a;
                c = 40+a;
                d = 60+a;
               int [] array = {a,b,c,d}

               //using enhanced for loop
               for(int ele : array){
                     System.out.println(ele +"\t\t"+ ele*ele)
                 } 
}

输出显示如下:

2 4

3 9

4 16

答案 3 :(得分:0)

使用printf。

public class Squarely {
    public static void main(String[] args) {
        for (int x = 1; x <= 20; ++x) {
            int a = x, b = 20+x, c = 40+a, d = 60+a;
            System.out.printf("%6d %6d %6d %6d %6d %6d %6d %6d%n",
                    a, a*a, b, b*b, c, c*c, d, d*d);
        }
    }
}