[英]How can I fix this program?
我一直在按照以下說明處理此程序:
車站信息 編寫一個程序,提供有關地鐵站的信息。 用戶應該首先輸入他們想要詢問多少個站,然后被允許命名多少個站。 該程序應該說明他們是否可以自由進入以及從入口到站台必須行駛的距離。 必須創建一個名為 Station 的新類型(記錄類型),並且關於一個站的每條單獨信息都應存儲在記錄的單獨字段中(其名稱 - 一個字符串,它們是否具有無步訪問 - 一個布爾值,和以米為單位的距離 - 一個整數)。
必須編寫一個單獨的方法,給定一個字符串(一個站名)作為參數返回一個包含有關該站的正確信息的字符串。 String 應該由調用方法打印。 程序運行示例:您的答案只需包括本示例中有關已知電台的信息。
How many stations do you need to know about? 4
What station do you need to know about? Stepney Green
Stepney Green does not have step free access.
It is 100m from entrance to platform.
What station do you need to know about? Kings Cross
Kings Cross does have step free access.
It is 700m from entrance to platform.
What station do you need to know about? Oxford Street
Oxford Street is not a London Underground Station.
What station do you need to know about? Oxford Circus
Oxford Circus does have step free access.
It is 200m from entrance to platform.
該程序沒有任何錯誤,但沒有顯示我需要的結果。
這是我使用相同示例得到的結果:
how many stations do you want to know about?
4
what station do you want to know about?
Stepney Green
Stepney Green does not have step free access. it is 100m away from the entrance to platform.
what station do you want to know about?
Kings Cross
Kings Cross does have step free access. it is 700m away from the entrance to platform.
what station do you want to know about?
Oxford Street
Oxford Street is not a London underground station
what station do you want to know about?
Oxford Circus
Oxford Circus does have step free access. it is 200m away from the entrance to platform.
“Stepney Green”和“stepney green”不是同一個字符串。 案例很重要。 您需要使用String
類中的equalsIgnoreCase
方法,例如
if (station.equalsIgnoreCase("stepney green")) {
System.out.println(stepneyGreenMessage);
}
關於輸出消息中缺少的換行符,您只需在需要它的地方添加一個文字\\n
即可轉到新行。 但我會像這樣重寫create_message
(它應該真正被稱為createMessage
以尊重 Java 命名約定)以避免重復:
public static String create_message(Station station) {
String message = station.name + " does ";
if (!station.step_free_access) { // try to avoid " == true" in if conditions
message += "not ";
}
message += "have step free access.\n"; // notice the "\n" to go to a newline
message += "It is " + station.distance_from_platform + "m away from the entrance to platform.";
return message;
}
還可以添加其他優化(例如使用StringBuilder
而不是String
但我認為它們超出了您嘗試解決的練習范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.