需求:1、写一个Cell类,该类有x、y属性,代表格子的行和列。2、该类提供向上移动、向下移动、向左移动、向右移动四种方法,由用户选择具体移动方向。3、要返回操作后的格子坐标位置。
注意:当操作的格子坐标越界后要复位,否则程序报错。(博主在写这个程序时遇到的问题就这个)。
import java.util.Scanner;
public class Cell {
public int x, y;
static Scanner scan = new Scanner(System.in);
public Cell() {
super();
}
public Cell(int x, int y) {
super();
this.x = x;
this.y = y;
}
public void moveUp() {// 上移
x--;
}
public void moveDown() {// 下移
x++;
}
public void moveLeft() {// 左移
y--;
}
public void moveRight() {// 右移
y++;
}
public void printWall(int x, int y) {// 打印格子方法
System.out.println("cell的位置(" + x + "," + y + ")");
for (int i = 1; i <= 10; i++) {// 打印列
System.out.print(" " + i + "");
}
System.out.println();
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");// 打印行
for (int j = 1; j <= 10; j++) {
if (i == x && j == y) {
System.out.print(" ■ ");
} else {
System.out.print(" □ ");
}
}
System.out.println();
}
operate();
}
public void operate() {//操作方法
while (true) {
System.out.println("请选择操作: 1、左移 2、右移 3、上移 4、下移 5、退出");
int selectOperation = scan.nextInt();
switch (selectOperation) {
case 1:
moveLeft();// 调用左移方法
if ((x >= 1 && x <= 10) & (y >= 1 && y < 11)) {// 横纵坐标在10*10的方格内
printWall(x, y);
} else {// 提示出界了
System.out.println("不能再往左边移了!!!");
y += 1;// 复位至限定方格内
break;
}
break;
case 2:
moveRight();// 调用右移方法
if ((x >= 1 && x <= 10) & (y >= 1 && y < 11)) {// 横纵坐标在10*10的方格内
printWall(x, y);
} else {// 提示出界了
System.out.println("不能再往右边移了!!!");
y -= 1;// 复位至限定方格内
break;
}
break;
case 3:
moveUp();// 调用上移方法
if ((x >= 1 && x < 11) & (y >= 1 && y <= 10)) {// 横纵坐标在10*10的方格内
printWall(x, y);
} else {// 提示出界了
System.out.println("不能再往上面移了!!!");
x += 1;// 复位至限定方格内
break;
}
break;
case 4:
moveDown();// 调用下移方法
if ((x >= 1 && x < 11) & (y >= 1 && y <= 10)) {// 横纵坐标在10*10的方格内
printWall(x, y);
} else {// 提示出界了
System.out.println("不能再往下面移了!!!");
x -= 1;// 复位至限定方格内
break;
}
break;
case 5:
exit();
break;
default:
System.out.println("操作错误!");
break;
}
}
}
public void exit() {// 退出方法
System.out.println("游戏结束!!");
scan.close();
System.exit(0);
}
}
再写一个测试类
ublic class CellTest {
public static void main(String[] args) {
Cell c = new Cell(5,5);// 创建Cell对象
c.printWall(5, 5);//设置初始横纵坐标
}
}
运行截图: