我是学生,是的,这是我的作业。我花了上周的时间审阅笔记,阅读这本书,并在网上研究相关主题,但我只是没有明白问题所在。你能告诉我我做错了什么吗?任何帮助将不胜感激。 (我只使用记事本和命令提示符。)Java新手 - 汽车应用
我得到的指导原则:创建一个由两个类组成的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
很抱歉,如果这个发布的所有靠不住的。我输入它很好,但预览看起来很扭曲。
+1为ID的好方法来识别输出; – MadProgrammer