0

所以这是我的课。我试图让 print() 方法在我的数组上方打印出一条水平线,在我的数组下方打印出另一条线。我还想在我的数组中的每个数字之间有垂直线。好的,我修复了我的水平线。现在我只是迷失了如何在我的数组的开头和结尾放置垂直线。

public class Array{

private int[] array;

public Array(int numElements)
{
    array = new int[numElements];
}

public void fill()
{
   for (int i = 0; i < array.length; i++)
    {
        array[i] = (int) (10*Math.random());
    } 
}

public void print()
{
    for(int x = 0; x < 2*array.length; x++)
    {
        System.out.print("-");
    }
    System.out.println();

    for(int i = 0; i < array.length; i++)
    {
        System.out.print(array[i]);
        if(i == array.length - 1)
        {
            System.out.println();
        }
        else
        {
            System.out.print("|");
        }
    }

    for(int n = 0; n < 2*array.length; n++)
    {
        System.out.print("-");

    }
    System.out.println();
}

public void sort()
{
    int n = array.length;
    boolean swapped;

    do
    {
        swapped = false;

        for(int i = 1; i < n; i++)
        {
            if(array[i-1] > array[i])
            {
                int tmp = array[i];
                array[i] = array[i-1];
                array[i-1] = tmp;
                swapped = true;
            }
        }
    } while(swapped);
}

public void printFrequency()
{
    int[] countArray = new int[10];
    for(int x : array)
    {
        countArray[x]++;
    }
    for(int i = 0; i < 10; i++)
    {
        System.out.println("There are " + countArray[i] + ", " + i + "'s ");
    }
}
}

这是我的输出:

Original:
-----------
1|5|9|3|3
-----------
Sorted:
-----------
1|3|3|5|9
-----------
Frequencies:
There are 0, 0's 
There are 1, 1's 
There are 0, 2's 
There are 2, 3's 
There are 0, 4's 
There are 1, 5's 
There are 0, 6's 
There are 0, 7's 
There are 0, 8's 
There are 1, 9's 

Original:
---------------------
7|0|5|2|0|1|8|0|7|7
---------------------
Sorted:
---------------------
0|0|0|1|2|5|7|7|7|8
---------------------
Frequencies:
There are 3, 0's 
There are 1, 1's 
There are 1, 2's 
There are 0, 3's 
There are 0, 4's 
There are 1, 5's 
There are 0, 6's 
There are 3, 7's 
There are 1, 8's 
There are 0, 9's 

我的输出应该是这样的:

Original:
-----------
|1|5|9|3|3|
-----------
Sorted:
-----------
|1|3|3|5|9|
-----------
Frequencies:
There are 0, 0's
There are 1, 1's
There are 0, 2's
There are 2, 3's
There are 0, 4's
There are 1, 5's
There are 0, 6's
There are 0, 7's
There are 0, 8's
There are 1, 9's

Original:
---------------------
|7|0|5|2|0|1|8|0|7|7|
---------------------
Sorted:
---------------------
|0|0|0|1|2|5|7|7|7|8|
---------------------
Frequencies:
There are 3, 0's
There are 1, 1's
There are 1, 2's
There are 0, 3's
There are 0, 4's
There are 1, 5's
There are 0, 6's
There are 3, 7's
There are 1, 8's
There are 0, 9's
4

2 回答 2

0

System.out.println();如果您不想在每个破折号字符后创建新行,请将行移到 for 循环之外。

于 2016-03-28T21:33:22.460 回答
0

摆脱println()这个循环:

for(int n = 0; n < array.length; n++)
{
    System.out.print("-");
    System.out.println();
}
于 2016-03-28T21:33:35.623 回答