2D阵列列的间距/对齐输出

时间:2016-04-05 20:32:42

标签: java arrays multidimensional-array

我有这两种方法可以生成随机值的二维数组而没有任何问题。

import java.util.concurrent.ThreadLocalRandom;

public class Guitar {

private int strings;
private int chords;

private double[][] song;

public Guitar(int mstrings, int mchords) {
    this.strings = mstrings;
    this.chords = mchords;
    song = new double[mstrings+1][mchords];
}

public void generateSong() {
    for (int i = 0; i < chords; i++) {
        for (int j = 0; j < song[i].length; j++) {
            song[i][j] = ThreadLocalRandom.current().nextDouble(27.5, 4186);
            song[strings][j] = ThreadLocalRandom.current().nextDouble(0, 3);
            if(song[i][j] == song[strings][j])
                System.out.printf(" %.1f", song[i][j]);
            else System.out.printf(" %.2f", song[i][j]);
        }
        System.out.println();
    }
}

//prints out the same table just with rows and columns swapped
public void simulateSong() {
    System.out.println("\nGuitar.simualateSong() ");
    for (int i = 0; i < chords; i++) {
        for (int j = 0; j < strings; j++) {
            System.out.printf(" %.2f", song[j][i]);
        }
        System.out.println();
    }
}

}

这里是使用命令行参数来确定大小的主要部分。

public class Songwriter {

public static void main(String[] args) throws InterruptedException {

    System.out.println("Guitar(): Generated new guitar with " + args[0] + " strings. Song length is " + args[1] + " chords.");

    String args0 = args[0];
    int strings = Integer.parseInt(args0);
    String args1 = args[1];
    int chords = Integer.parseInt(args1);

    Guitar guitarObj1 = new Guitar(strings, chords);
    guitarObj1.generateSong();
    guitarObj1.simulateSong();

}

}

我唯一的问题是间距/对齐输出。这是一个样本运行,其中3和4作为行数和列数的参数

Guitar(): Generated new guitar with 3 strings. Song length is 4 chords.
 1103.75 1133.24 3559.35 330.26
 744.83 3850.74 3493.20 1848.97
 3908.79 2548.87 1771.52 2761.32
 0.5 0.7 2.0 1.6

Guitar.simualateSong() 
 1103.75 744.83 3908.79
 1133.24 3850.74 2548.87
 3559.35 3493.20 1771.52
 330.26 1848.97 2761.32

我想格式化输出如此

Guitar(): Generated new guitar with 3 strings. Song length is 4 chords.
 1103.75 1133.24 3559.35  330.26
  744.83 3850.74 3493.20 1848.97
 3908.79 2548.87 1771.52 2761.32
     0.5     0.7     2.0     1.6

Guitar.simualateSong() 
 1103.75  744.83 3908.79
 1133.24 3850.74 2548.87
 3559.35 3493.20 1771.52
  330.26 1848.97 2761.32

感谢任何帮助。感谢。

0 个答案:

没有答案