(java)如何获得这样的输入

isr3a4wc  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(231)

我需要一个代码,读取将要完成的测试数量,然后读取每个测试矩阵上的值。
输入:

测试1
0 20 10
1 12 34
1 5 6
测试2
0 22 10
1 10 34
0 0 0
测试3
0 10 10
0 0 20
0 0 0
我的尝试:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Number of tests");
    int n = input.nextInt();

    String[] name = new String[n];
    int test[][] = new int[n][3];

    for (int i = 0; i < n; i++) {

        System.out.println("Name of the test" + i);

        name[i] = input.nextLine();
        System.out.println("Values");
        for (int j = 0; j < 3; j++) {
            test[i][j] = input.nextInt();
        }
    }
}
wwwo4jvm

wwwo4jvm1#

你需要一个三维数组而不是二维数组,因为每个测试都有一个二维数组。
演示:

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        final int ROWS = 3, COLS = 3;
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        int test[][][] = new int[n][ROWS][COLS];
        for (int i = 0; i < n; i++) {
            System.out.println("Test " + (i + 1));
            for (int j = 0; j < ROWS; j++) {
                for (int k = 0; k < COLS; k++) {
                    test[i][j][k] = input.nextInt();
                }
            }
        }

        // Display
        System.out.println("Displaying...");
        for (int i = 0; i < n; i++) {
            System.out.println("Test " + (i + 1));
            for (int j = 0; j < ROWS; j++) {
                for (int k = 0; k < COLS; k++) {
                    System.out.printf("%4d", test[i][j][k]);
                }
                System.out.println();
            }
        }
    }
}

示例运行:

3
Test 1
0 20 10
1 12 34
1 5 6
Test 2
0 22 10
1 10 34
0 0 0
Test 3
0 10 10
0 0 20
0 0 0
Displaying...
Test 1
   0  20  10
   1  12  34
   1   5   6
Test 2
   0  22  10
   1  10  34
   0   0   0
Test 3
   0  10  10
   0   0  20
   0   0   0

相关问题