编译器无法识别类字符串值等于另一个字符串值

问题描述

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",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”作为checkinfo(choice)的选择输入时,它不能识别为{{ 1}}在方法stationName == station.name

Intellij调试器在checkInfo(stationName //choice)上读取

-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哈希= 0 hashisZero = 0

-info = null

-站= {Station @ 994}->名称=“斯蒂芬·格林”,通过=假,距离= 100

-station.name =“ Stepney Green”->值= {byte [13] @ 999]其余为零

在语句旁边显示stationName:“ Stepney Green”站:Station @ 994。而不是打印出stationName + infoAboutStation,而是转到else站并打印“ Stepney Green不是伦敦地铁站”。我很困惑为什么。另外,如果您不介意帮助我使此代码更高效,更好。

解决方法

您应该使用String比较equals()
取代这个

if(stationName == station.name)

作者

if(stationName.equals(station.name))
,

已修复更改为

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

感谢您的帮助