gpt4 book ai didi

Java Scanner 输入不等于自身?

转载 作者:行者123 更新时间:2023-12-03 18:36:44 25 4
gpt4 key购买 nike

我正在编写一个循环,该循环将在扫描器收到字符串值“end”时退出。但是,当使用“结束”值进行测试时,循环会继续。从逻辑上讲,如果文件 = 输入,则 if(file=="end") 为假,即使我输入的是 end!我的代码中是否存在明显的错误?

String file = "";
Scanner in = new Scanner(System.in);
ArrayList<Integer> fileInput = new ArrayList<Integer>();

while(file!="end") {
// Scan for filename/end program
System.out.println("Provide the name of a file in the \"bin/\" folder, i will assume it's .txt");
file = in.nextLine();

System.out.println("." + file + ".");
if(file!="end") {
file= "bin/" + file + ".txt";

// start reading
try {
// If file found then carry on
BufferedReader openFile = new BufferedReader(new FileReader(file));
fileInput = readIn(openFile);
int lowerBound = getLower(fileInput);
int upperBound = getUpper(fileInput);

System.out.println("Lower Bound: " + lowerBound);
System.out.println("Upper Bound: " + upperBound);

// file not found
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
}
}
System.out.println("Goodbye!");
System.exit(0);

最佳答案

在 Java 中,您必须使用 .equals() 来实现字符串相等;否则它会进行引用比较。

String s1 = "end";
String s2 = "end"; // different string in memory
s1 == s2 // false: not the same string
s1.equals(s2) // true: have the same characters
"end".equals(s1) // also true
"end" == s1 // false

是的,这很糟糕。

关于Java Scanner 输入不等于自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2158695/

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