gpt4 book ai didi

java - 在 if 语句中使用字符串和逻辑运算符

转载 作者:行者123 更新时间:2023-12-01 23:40:21 26 4
gpt4 key购买 nike

我刚开始学习 Java。我大约一周前开始学习,每天花大约 10 个小时学习,我不确定我是否落后于我“应该”的水平(我正在处理的另一个问题)我知道我的代码可能不是最有效的,但我必须从某个地方开始,并且我从上周阅读的信息宇宙中从内存中输入了大部分内容。现在,我只是想制作游戏或应用程序来帮助巩固编程概念。运用我所学到的知识并使这些信息具有相关性。

我的问题是,至关重要的是,为什么我的“if”语句直接转到“else”?

public class ClassSelect {

public static String className;

public static void pickPlayer() {

Scanner scan = new Scanner(System.in);
System.out.println("Pick your class." + "\n" + "[F]ighter" + "\n"
+ "[W]izard");
String scanClass = scan.nextLine();

if ((scanClass == "f") || (scanClass == "F")) {
System.out.println("You picked the Fighter");
String classNameF = "Fighter";
className = classNameF;
try {
File file = new File("saveData.txt");
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write(className);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}

else if ((scanClass == "w") || (scanClass == "W")) {
System.out.println("You picked the Wizard");
String classNameW = "Wizard";
className = classNameW;
try {
File file = new File("saveData.txt");
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write(className);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("You didn't choose either.");
}
}

最佳答案

对于字符串比较,必须使用Object类的equals方法。你的 if 语句将变得像 - if(scanClass.equals("f"))...

请记住,== 比较的是引用而不是实际对象。

关于java - 在 if 语句中使用字符串和逻辑运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18053620/

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