如何在2d数组中打印特定行

时间:2017-02-01 23:31:39

标签: java arrays multidimensional-array

我正在尝试在我的应用程序中打印所有4行以保持分数,而我目前只是打印了我的数组的所有索引。是否有更简洁的方法来打印出一行索引?

package bowlingmain;

import java.util.Scanner;


public class BowlingMain {


    private static final int NUMBER_OF_ENDS = 10;
    private static String players[] = new String[4];
    private static int scoring[][] = new int[4][NUMBER_OF_ENDS];
    private static String output = "";


    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter player #1");
        players[0] = input.nextLine();
        System.out.println("Enter player #2");
        players[1] = input.nextLine();
        System.out.println("Enter player #3");
        players[2] = input.nextLine();
        System.out.println("Enter player #4");
        players[3] = input.nextLine();



        for(int j = 0; j <= NUMBER_OF_ENDS; j++){
            for(int i = 0; i < scoring.length; i++){
            System.out.println("Enter in score for "+players[i]+" ---->");
                scoring[i][j] = input.nextInt();
                input.nextLine();
                System.out.println("Current Score \n");
                output = players[0]+" "+scoring[0][0]+ " " + scoring[0][1]+" "+scoring[0][2]+ " " + scoring[0][3]+" "+scoring[0][4]+ " " + scoring[0][5]+" "+scoring[0][6]+ " " + scoring[0][7]+" "+scoring[0][8]+ " " + scoring[0][9]+"\n"+
                         players[1]+" "+scoring[1][0]+ " "+ scoring[1][1]+" "+scoring[1][2]+ " " + scoring[1][3]+" "+scoring[1][4]+ " " + scoring[1][5]+" "+scoring[1][6]+ " " + scoring[1][7]+" "+scoring[1][8]+ " " + scoring[1][9]+"\n"+
                         players[2]+" "+scoring[2][0]+ " " + scoring[2][1]+" "+scoring[2][2]+ " " + scoring[2][3]+" "+scoring[2][4]+ " " + scoring[2][5]+" "+scoring[2][6]+ " " + scoring[2][7]+" "+scoring[2][8]+ " " + scoring[2][9]+"\n"+
                         players[3]+" "+scoring[3][0]+ " " + scoring[3][1]+" "+scoring[3][2]+ " " + scoring[3][3]+" "+scoring[3][4]+ " " + scoring[3][5]+" "+scoring[3][6]+ " " + scoring[3][7]+" "+scoring[3][8]+ " " + scoring[3][9]+"\n";
                System.out.println(output);

           }
        }

    }

}

1 个答案:

答案 0 :(得分:0)

您的变量令人困惑,使用数组的实际值而不是您的数组,以便更容易理解迭代和索引。

    String output = "";

    for(int i = 0; i < scoring.length; i++)
    {
        output += players[i] + ": ";
        for(int j = 0; j < scoring[i].length; j++)
        {
            output += scoring[i][j] + " ";
        }
        System.out.println(output);
        output = "";
    }