首页 > 解决方案 > 编译器无法识别类字符串值等于另一个字符串值

问题描述

public class Station {
    String name;
    boolean pass;
    int distance;

    // method to create a new Station taking the arguments of the name,pass and distance in the parameter
    public static Station createStation(String name, boolean pass, int distance) {  
    }

    // Array list containing all the Stations in London we will use
    static Station[] StationList = {createStation("Stepney Green", false, 100), createStation("Kings Cross", true, 700), createStation(
            "Oxford Circus", true, 200)};

    public static String infoAboutStation(Station station) {
        String message;
        if (station.pass)
            message = //string message
        else
            message = //string message
        return message;
    }

    public static String checkInfo(String stationName){
        String info = null;

        for(Station station : StationList){     
            if(stationName == station.name) { //it does not recognise it to be the same for some reason
                info = stationName + infoAboutStation(station);
            }
            else
                info = stationName + " message ";
        }
        return info;
    }

    public static void printInfo(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("How many... ");
        int totalResponses = Integer.parseInt(scanner.nextLine());

        String choice;
        for(int i = 0; i < totalResponses; ++i){
            System.out.println("Enter a station: ");
            choice = scanner.nextLine();
            System.out.println(checkInfo(choice));
        }
    }
    // psvm(String[] args)
}

所以程序运行良好,但是当我们使用“Stepney Green”、“Kings Cross”、“Oxford Circus”作为选择 at 的输入时checkinfo(choice),它不认为它stationName == station.name在方法中是相同的checkInfo(stationName //choice)

Intellij 调试器在stationName == station.name

-StationList = {Station[3]@980} -> 0 = {Station@994} 1 = {Station@997} 2 = {Station@998}

-static -> StationList = {Station[3]@980}

-stationName = "Stepney Green" 值 = {byte[13]@996} 编码器 = 0 hash = 0 hashisZero = 0

-信息=空

-station = {Station@994} -> name = "Stepney Green",通过 = false,距离 = 100

-station.name = "Stepney Green" -> value = {byte[13]@999] 剩余为零

在声明旁边,它说 stationName:“Stepney Green”站:Station@994。它没有打印出 stationName + infoAboutStation,而是转到 else 站并打印“Stepney Green is not a London Underground Station”。我很困惑为什么。另外,如果您不介意帮助我使此代码更高效、更好。

标签: javaarraysif-statementdebuggingcompare

解决方案


固定更改为

for(Station station : StationList){
    if(stationName.equals(station.name)) {
        info = stationName + infoAboutStation(station);
        break;
    }
}

谢谢您的帮助


推荐阅读