java - 为什么使用 java 扫描仪从 txt 文件中读取的字符串不等于相同的字符串?
问题描述
下面是我的代码,目标是从 txt 文件中读取指令以使 java 机器人执行它们。当将 if 语句的任何部分更改为 != 时,机器人部分工作,因此我必须认为字符串在某种程度上不相等。
public void interpretGoo() throws AWTException, FileNotFoundException,
InterruptedException{
Scanner scanner = new Scanner( new File("instruct.txt") );
String in;
String instruct = "";
while(scanner.hasNextLine()== true){
in = scanner.nextLine();
instruct+= in;
}
scanner.close();
String[] instructSet= instruct.split("-");
System.out.println("String: " + instruct);
String[] command= new String[10];
for(int i= 0; i< instructSet.length;i++){
command= instructSet[i].split(" ");
System.out.println("Set: " + instructSet[i]);
System.out.println("Word: " + command[0]);
if(command[0].trim()== "key"){
keyboardHandler(command[1].charAt(1));
Thread.sleep(150);
}else if(command[0].trim()== "clickL"){
accuMouse(Integer.parseInt(command[1]),Integer.parseInt(command[2]), 1, false);
}else if(command[0].trim()== "clickR"){
accuMouse(Integer.parseInt(command[1]),Integer.parseInt(command[2]), 0, true);
}else{
System.out.println("FAIL");
continue;
}
}
}
输出:
String: clickL 728 1062-clickL 540 382-key h-key e-key l-key l-key o-
Set: clickL 728 1062
Word: clickL
FAIL
Set: clickL 540 382
Word: clickL
FAIL
Set: key h
Word: key
FAIL
Set: key e
Word: key
FAIL
Set: key l
Word: key
FAIL
Set: key l
Word: key
FAIL
Set: key o
Word: key
FAIL
根据输出,字符串相同但未通过检查,任何帮助将不胜感激!
解决方案
您需要.equals
在 Java 中用于字符串比较。如果您只使用 ,您会发现许多相同的字符串彼此不相等==
。大多数对象也是如此。一般来说,.equals()
在 Java 中使用相等更安全。
推荐阅读
- powerbi - 导入excel文件时Power Bi日期错误
- javascript - 如何从嵌入在 MongoDB 对象数组中的数组中提取值?
- angular - Angular / Rxjs如何订阅具有不同参数的循环中的函数
- c++ - 释放 3 维向量 C++
- javascript - 将字符串值转换为 int (esp32)
- mysql - 使用一个接一个的值进行查询,为一堆值工作
- sql - 将每行中的值与列的平均值进行比较 (SQL)
- javascript - 从 QRCode 扫描时在输入值中添加逗号
- mysql - JPA - 使用特殊章程运行“插入”的 sql NativeQuery 失败
- c# - c# MySQL Connect I gоt a System.NullReferenceException Object reference not set an instance of an object