首页 > 解决方案 > 我该如何修复这个程序?

问题描述

我一直在使用这些说明来开发这个程序:

车站信息 编写一个程序,提供有关地铁站的信息。用户应首先输入他们希望询问的电台数量,然后允许命名这些电台。程序应该说明他们是否有无障碍通道以及从入口到平台必须经过的距离。必须创建一个名为 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.

标签: javafor-loop

解决方案


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

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;
}

还可以添加其他优化(例如使用 aStringBuilder而不是 a,String但我认为它们超出了您尝试解决的练习范围。


推荐阅读