gpt4 book ai didi

java - 我希望程序使用多个字符串读取用户输入

转载 作者:行者123 更新时间:2023-11-30 08:07:06 24 4
gpt4 key购买 nike

我希望读取用户输入,然后 if 语句将从那里接管但它没有读取字符串。我将在不同区域添加更多站点。帮助!

import java.util.*;

public class centralline {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("What station do you need to know the zone of? ");
String answer = input.nextLine();
String zone1 = "Liverpool Street" + "Oxford Street" + "Bank";
String zone2 = "Mile End" + "Stratford";

{
if (zone1.equals(answer)) {
System.out.println(answer + " is in Zone 1");

} else if (zone2.equals(answer)) {
System.out.println(answer + " is in Zone 2");
} else
System.out
.println("is"
+ answer
+ "a Loodon underground station? Maybe check your spelling. ");
}
}
}

最佳答案

要么将您的区域存储在字符串数组中,然后检查答案是否在数组中,要么使用.contains( ) 不是 .equals()

if (zone1.contains(answer))

...

 } else if (zone2.contains(answer)) {

或者:

String[] zone1 = new String[3];
zone1[0] = "Liverpool Street";
zone1[1] = "Oxford Street";
zone1[2] = "Bank";

for(String a : zone1)
{
if (a.equals(answer))
{
System.out.println( answer+" is in Zone 1");
break;
}
}

只需对其他区域重复这些步骤...创建一个 boolean 变量来跟踪是否在其中一个 区域 中找到了 answer >.

关于java - 我希望程序使用多个字符串读取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33898055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com