ADGJ20
ADGJ20

Reputation: 11

(Java) How to get an input like this

I need a code that reads the number of tests that will be done and then read values on a matrix for each test.

INPUT:

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

My attempt:

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();
        }
    }
}

Upvotes: 1

Views: 74

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79025

You need a 3-D array instead of a 2-D because for each of the test has a 2-D array under it.

Demo:

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();
            }
        }
    }
}

A sample run:

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

Upvotes: 1

Related Questions