【发布时间】:2021-04-21 00:55:19
【问题描述】:
我没有让这个工作。这是面向对象的。向上、向下、向左或向右移动时,我应该在网格中获取 (x,y) 坐标。我需要 toString 始终为我采取的每一步更新。我更喜欢在键盘上使用箭头键,但我不知道如何。如果有人知道这对程序会很好。我必须能够 - 例如 - 按向上、然后向下、然后向上而不停止。
package stateandbehavior;
import java.util.*;
public class Location {
int x;
int y;
public void up() {
boolean run = true;
while (run) {
Scanner tast = new Scanner(System.in);
String tas = tast.nextLine();
if (tas == "W" || tas == "w") {
y-=1;
}else {
run = false;
}
}
}
public void down() {
boolean run = true;
while (run) {
Scanner tast = new Scanner(System.in);
String tas = tast.nextLine();
if(tas == "S" || tas == "s") {
y+=1;
} else {
run = false;
}
}
}
public void right() {
boolean run = true;
while (run) {
Scanner tast = new Scanner(System.in);
String tas = tast.nextLine();
if (tas == "D" || tas == "d") {
x+=1;
}else {
run = false;
}
}
}
public void left() {
boolean run = true;
while(run)
Scanner tast = new Scanner(System.in);
String tas = tast.nextLine();
if(tas == "A" || tas == "a") {
x-=1;
}else {
run = false;
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public String toString() {
return "(" + x + ","+ y + ")";
}
public static void main(String[] args) {
Location Loc = new Location();
Loc.up();
Loc.down();
Loc.right();
Loc.left();
Loc.getX();
Loc.getY();
System.out.println(Loc);
}
}
【问题讨论】:
-
你的代码太糟糕了。 a) 这是错误的。错误的概念。生病发布解决方案。 b)格式(尤其是意图)非常糟糕。使用 Eclipse 或 IntelliJ,使用它们带来的格式化功能。 c) 代码有句法/结构错误。大括号放置错误。 d) 命名约定是小写的对象名称,即它应该是
Location loc = new Location()
标签: java