我是一名学生,是的,这是我的家庭作业。上周我一直在复习笔记,阅读本书,并在网上研究相关主题,但我就是不明白问题出在哪里。你能告诉我我做错了什么吗?任何帮助将不胜感激。(我只使用记事本和命令提示符。)
我得到的指导方针:创建一个包含两个类的 Java 应用程序。第一类将是您的应用程序类。第二类将是一个名为 Car 的类。您的应用程序将创建一个名为 nova 的 Car 实例并驱动它。
用车规则:
- 如果汽车未启动,您将无法驾驶(向控制台发送错误消息)。
- 如果汽车未启动,您将无法停车(向控制台发送错误消息)。
- 如果汽车已经启动,则无法启动(向控制台发送错误消息)。
- 一旦你告诉汽车开车,你唯一能做的就是停下来(向控制台发送消息)
- 一旦您调用停止,汽车将返回初始状态,用户必须在尝试执行任何其他功能之前启动汽车。(向控制台发送消息)
showState 方法的目的是提供一种检查汽车状态的方法。它应该构建一条消息,然后可以将其发送到控制台。
我的代码:
public class MyAppAssignment3
{
public static void main (String[] args)
{
System.out.println("Scenario 1");
Car nova1 = new Car();
nova1.start();
nova1.showState();
nova1.drive();
nova1.stop();
nova1.showState();
System.out.println("");
System.out.println("Scenario 2");
Car nova2 = new Car();
nova2.showState();
nova2.drive(); //needs to send error message - can't drive a car that's not started
nova2.stop();
nova2.showState();
System.out.println("");
System.out.println("Scenario 3");
Car nova3 = new Car();
nova3.showState();
nova3.start();
nova3.showState();
nova3.stop(); //needs to send error message - can't stop a car that's not driving
nova3.showState();
nova3.drive();
nova3.stop();
}
}
class Car
{
private boolean isStarted;
private boolean isDriving;
private boolean isStopped;
private String showState;
public Car()
{
this.showState = showState;
}
public void start()
{
isStarted = true;
isDriving = false;
isStopped = false;
System.out.println("The car is " + this.showState);
}
public void drive()
{
isStarted = false;
isStopped = false;
isDriving = true;
System.out.println("The car is " + this.showState);
}
public void stop()
{
isStopped = true;
isStarted = false;
isDriving = false;
System.out.println("The car is " + this.showState);
}
public String showState()
{
if (isStarted)
{
showState = "started";
}
else if(isDriving)
{
showState = "driving";
}
else if(isStopped)
{
showState = "stopped";
}
System.out.println("The car is " + this.showState);
return showState;
}
}
我的输出(这都是错误的 - 值不正确):
Scenario 1
The car is null
The car is started
The car is started
The car is started
The car is stopped
Scenario 2
The car is null
The car is null
The car is null
The car is stopped
Scenario 3
The car is null
The car is null
The car is started
The car is started
The car is stopped
The car is stopped
The car is stopped
抱歉,如果这发布的所有内容都不稳定。我打字很好,但预览看起来很糟糕。