【发布时间】:2018-07-16 18:17:06
【问题描述】:
以下是我的代码,目标是从 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
根据输出,字符串相同但未通过检查,我们将不胜感激!
【问题讨论】:
-
只有字符串的内容是相同的。但不是对象本身。
==比较 identity,而不是 content。使用equals比较内容。另请注意,与true或false的比较已过时:while (foo == true)与while (foo)相同。
标签: java arrays if-statement text-files java.util.scanner