我的任务是开发一个测试我的 Robot 类的应用程序。测试应用程序将询问用户机器人名称。然后它将使用该名称实例化一个 Robot 对象。然后,应用程序将使用循环要求用户输入移动方向(x 或 y)和距离。当用户输入 q 方向(退出)时,循环将终止。循环完成后,程序将显示机器人的最终位置和总行驶距离。
我的主要问题是尝试使用我的 Robot 类,并在涉及 if 语句时在我的 Prog3 类中测试它。这是我的机器人类(class):
public class Robot {
private String name;
private int xPosition;
private int yPosition;
private int totalDistance;
public Robot(String name, int xPosition, int yPosition, int totalDistance){
super();
this.name = name;
this.xPosition = 0;
this.yPosition = 0;
this.totalDistance = totalDistance;
}
public String getName() {
return name;
}
public int getxPosition() {
return xPosition;
}
public int getyPosition() {
return yPosition;
}
public int getTotalDistance() {
return totalDistance;
}
public void moveX(int distance){
xPosition += distance;
totalDistance += Math.abs(distance);
}
public void moveY(int distance){
yPosition += distance;
totalDistance += Math.abs(distance);
}
}
现在这是我的 Prog3 类(class):
import java.util.Scanner;
public class Prog3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Robot robot = new Robot();
//asks the user for robots name
System.out.print("Enter robots name; ");
Robot.name = in.nextLine();
//asks the user to move the robot
System.out.print("Direction of move (x/y/q): ");
String move = in.nextLine();
if( move.equals("x") ){
System.out.print("Distance: ");
}
else if( move.equals("y") ){
System.out.print("Distance: ");
}
else{
}
}
}
如您所见,由于我完全陷入困境,我的 Prog3 类(class)尚未完成。非常感谢您抽出宝贵的时间,我们非常感激。
最佳答案
“当用户输入 q 方向(退出)时,循环将终止。”。您的程序没有循环:
Scanner in = new Scanner(System.in);
Robot robot = new Robot();
//asks the user for robots name
System.out.print("Enter robots name; ");
Robot.name = in.nextLine();
//asks the user to move the robot
System.out.print("Direction of move (x/y/q): ");
String move = in.nextLine();
if( move.equals("x") ){
System.out.print("Distance: ");
}
else if( move.equals("y") ){
System.out.print("Distance: ");
}
else{
}
此代码段只会运行一次...如果您希望它循环,您需要一个实际的
While(<Conditional>) {
// your code here
// a break point to exit the loop ( in your case "q" as the input string )
} // end while...
另外,我有点困惑,因为你问题的措辞有点含糊。您的问题的本质到底是什么?
关于java - 带 setter/getter 的 if 语句的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35446264/