我正在制作这样的黑白棋游戏:
import java.util.Arrays;
import java.util.Scanner;
public class test{
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Please enter the board size (4 or above and even number) : ");
int num = sc.nextInt();
int rows = num; // Number of rows
int cols = num; // Number of columns
if (num % 2 == 1 || num < 4) {
System.out.println("Error - input number should be 4 or above and even number.");
} else {
int[][] reversigame = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(reversigame[i][j] + " ");
}
reversigame[num - num / 2][num - num / 2] = 1;
reversigame[(num - num / 2) - 1][(num - num / 2) - 1] = 1;
reversigame[(num - num / 2)][(num - num / 2) - 1] = 2;
reversigame[(num - num / 2) - 1][(num - num / 2)] = 2;
System.out.println();
}
但我想在使用扫描仪时使用空格键来分隔新的行和列,如下所示:
System.out.print("Please enter the position of '1' (row col): ");
int bcp = sc.nextInt();//bcp=black chess place
int b = 1;//black chess = 1
String[] digits = String.valueOf(bcp).split(" ");
但在我执行下一步时无法将其更改为行和列:
if (bcp > 5 || bcp < 0) {/*Control variables between 0 and 5*/
System.out.println("Error - input number should be 0 to 5!");
}
for (; reversigame[bcp + 1][bcp] == 2 || reversigame[bcp][bcp + 1] == 2 || reversigame[bcp - 1][bcp] == 2 || reversigame[bcp][bcp + 1] == 2;) {/*Check the black chess is or is't near the white chess*/
reversigame[bcp][bcp] = b;
System.out.println(Arrays.deepToString(reversigame));
if (reversigame[bcp + 1][bcp] != 2 || reversigame[bcp][bcp+ 1] != 2 || reversigame[bcp - 1][bcp] != 2 || reversigame[bcp][bcp + 1] != 2) {
System.out.println("Error - invalid move");
break;
}
}
那么,如何在一个句子中添加行和列,同时使用空格键分隔它们?
您可以用空格分隔数字并按顺序读取两个整数:
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println("result = " + (a + b));
输出如下:
2 5
result = 7