首页 > 解决方案 > 为什么使用 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

根据输出,字符串相同但未通过检查,任何帮助将不胜感激!

标签: javaarraysif-statementtext-filesjava.util.scanner

解决方案


您需要.equals在 Java 中用于字符串比较。如果您只使用 ,您会发现许多相同的字符串彼此不相等==。大多数对象也是如此。一般来说,.equals()在 Java 中使用相等更安全。


推荐阅读