我是學生,是的,這是我的作業。我花了上週的時間審閱筆記,閱讀這本書,並在網上研究相關主題,但我只是沒有明白問題所在。你能告訴我我做錯了什麼嗎?任何幫助將不勝感激。 (我只使用記事本和命令提示符。)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