从应用程序打印错误的结果

时间:2013-12-03 01:21:49

标签: java println

我遇到了打印结果的问题。我的程序现在应该左右打印2列,但由于某种原因,一面打印方式低于预期。我不确定我在哪里出错了。

public class AscendDescend
{
    public static void main(String[] args)
    {
        String ss[] = {"Bill", "Mary", "Lee", "Agenes", "Alfred", "Thomas", "Alvin", "Bernard", "Ezra", "Herman"};
        //String ss[] = {"Bill", "Mary", "Lee", "Agenes", "Alfred", "Thomas", "Alvin", "Bernard", "Ezra", "Herman"};

        System.out.println("Ascend\tDescend" + "\n");

        for(int i = 0; i < ss.length; i++)
        {
            System.out.println(ss[i]);
        }

        for(int j = ss.length - 1; j >= 0; j--)
        {
            System.out.println("\t" + ss[j]);
        }
    }
}

2 个答案:

答案 0 :(得分:3)

你是:

  • 按升序打印出所有值 - 每个值都在一个单独的行上;然后
  • 按降序打印出所有值 - 每个值都以标签和新行为前缀。

您似乎想要做的是在同一行打印出升序和降序项目。像这样:

public class AscendDescend
{
    public static void main(final String[] args)
    {
        final String ss[] = {"Bill", "Mary", "Lee", "Agenes", "Alfred", "Thomas", "Alvin", "Bernard", "Ezra", "Herman"};

        System.out.println("Ascend\tDescend" + "\n");
        final int l = ss.length;

        for(int i = 0; i < l; i++)
        {
            System.out.println(ss[i] + "\t" + ss[l-1-i]);
        }
    }
}

这个输出是:

Ascend  Descend

Bill    Herman
Mary    Ezra
Lee Bernard
Agenes  Alvin
Alfred  Thomas
Thomas  Alfred
Alvin   Agenes
Bernard Lee
Ezra    Mary
Herman  Bill

答案 1 :(得分:0)

System.out.println会打印一个新行。这将使得上升和下降的值 不在同一条线上。

如果您想要并排打印2列。您可以在同一个for循环中打印上升和下降的值。

像,

    System.out.println("Ascend\tDescend" + "\n");

    for (int i = 0, len = ss.length; i < ss.length; i++) {
        System.out.printf("%s\t%s \n", ss[i], ss[len - 1 - i]);
    }

然后控制台中的输出如下:

Ascend  Descend

Bill    Herman 
Mary    Ezra 
Lee     Bernard 
Agenes  Alvin 
Alfred  Thomas 
Thomas  Alfred 
Alvin   Agenes 
Bernard Lee 
Ezra    Mary 
Herman  Bill