我正在開發一個小遊戲,用戶必須選擇5個字符中的一個(S,M,A,R或T)並將其插入5x5二維數組中。如果用戶輸入一個無效的數字或字符,程序會說這是一個無效的字符,並且不會插入它。除了輸入正確字符的字符之外,它還可以處理所有字符,但仍然顯示爲無效字符。數組中的唯一字符集
import java.util.Scanner;
class program{
public static void main(String[] args){
char[][] table = new char[5][5];
table[0][0] = 'S';
table[0][1] = 'M';
table[0][2] = 'A';
table[0][3] = 'R';
table[0][4] = 'T';
table[1][1] = 'T';
table[1][2] = 'S';
table[1][3] = 'M';
table[2][2] = 'R';
table[2][4] = 'S';
table[3][1] = 'S';
table[3][2] = 'M';
table[4][2] = 'T';
table[4][3] = 'S';
int rows = 5;
int columns = 5;
for(int k = 0; k>=0; k++){
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
System.out.print(table[i][j] + " ");
}
System.out.println();
}
System.out.println("Enter a row (1-5): ");
Scanner scRow = new Scanner(System.in);
int m = scRow.nextInt();
System.out.println("Enter a column (1-5): ");
Scanner scCol = new Scanner(System.in);
int n = scCol.nextInt();
System.out.println("Enter a letter (S, M, A, R or T): ");
Scanner scChar = new Scanner(System.in);
char c = scChar.next().charAt(0);
if (m < 1 || m > 5){
System.out.println("Invalid: Enter a valid row. ");
}
if (n < 1 || n > 5){
System.out.println("Invalid: Enter a valid column. ");
}
if (c != 'S' || c != 'M' || c != 'A' || c != 'R' || c != 'T'){
System.out.println("Invalid: Enter a valid character. ");
}
table[(m-1)][(n-1)] = c;
}
}
}
我知道它是與我的if語句,但我不確定怎麼做才能得到預期的結果if語句改變。
Example output:
S M A R T
T S M
R S
S M
T S
Enter a row (1-5): **3**
Enter a column (1-5): **2**
Enter a letter (S, M, A, R or T): **A**
Invalid: Enter a valid character.
另一個問題,如果有人能夠幫助在用戶獲取二維數組完成,它說恭喜,你說對了我創造的最終聲明。爲此,用戶必須使S M A R和T在任意方向上以5個字符的行對齊。
感謝您花時間閱讀本文!
'創建一個結束語句,用戶獲得2d數組完成,它說祝賀,你明白了。'你不能只計算用戶輸入有效字符的次數嗎? –