Introduction to Java Programming編程題8.36

運行結果:

Enter number n: 4
Enter 4 rows of letters separated by spaces:
A B C D
B A D C
C D B A
D C A B
The input array is a Latin square.

Enter number n: 3
Enter 3 rows of letters separated by spaces:
A F D
Wrong input: the letters must be from A to C

Many.java

import java.util.Scanner;

class Many {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter number n: ");
        int n = input.nextInt();

        char[][] a = new char[n][n];
        System.out.println("Enter " + n + " rows of letters separated by spaces: ");
        readMatrix(a);
    }

    public static void readMatrix(char[][] a) {
        String temp;
        Scanner input = new Scanner(System.in);

        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                temp = input.next();
                a[i][j] = temp.charAt(0);
                if (i == 0 && a[i][j] != 'A' + j) {
                    System.out.print("Wrong input: the letters must be from A to C.");
                    break;
                }
            }
        }

        System.out.println("The input array is a Latin square.");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章