我该如何修复该程序?

时间:2020-11-10 10:49:01

标签: java for-loop

我一直在按照以下说明进行此程序的工作:

车站信息编写一个程序,该程序提供有关地下车站的信息。的 用户应首先输入他们希望询问的电台数量,然后再命名 很多站。程序应说明他们是否可以无级访问以及距离 必须从入口进入平台。必须创建一个称为Station的新类型( 记录类型),并且有关电台的每条单独信息都应存储在单独的位置 记录的字段(其名称-字符串,是否可以无级访问-布尔值,以及 距离(以米为单位-整数)。

必须编写一个单独的方法,该方法给定字符串(站名)作为参数返回字符串 包含有关电台的正确信息。字符串应在调用时打印 方法。该程序的示例运行:您的答案仅需 包括本示例中有关已知电台的信息。

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.

1 个答案:

答案 0 :(得分:1)

“ Stepney Green”和“ Stepney Green”不是同一字符串。案件很重要。您需要使用String类中的equalsIgnoreCase方法,例如

if (station.equalsIgnoreCase("stepney green")) {
    System.out.println(stepneyGreenMessage);
}

关于输出消息中缺少的换行符,您只需在原语\n处添加到新行的位置即可。但是我会这样重写create_message(为了尊重Java命名约定,应将其实际上称为createMessage),以避免重复:

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,但我认为它们超出了您要解决的练习范围。

相关问题