Java字符串比较ALWAYS返回false

时间:2015-10-06 20:52:02

标签: java string

我在java中编写一个程序,它将使用数字和字母生成一组随机字符,逐个输出,在每个字符后清除控制台,将字符附加到字符串,并要求用户重复序列

我的问题是,如果程序说'a'并要求输入,即使输入'a',它也会返回错误。以下是生成和测试字符串的代码:

public void generateSeq() {
        try {
            Random rand = new Random();
            for (int i = 0; i < numChars; i++) {
                Robot bot = new Robot();
                c = characters.charAt(rand.nextInt(characters.length()));
                System.out.print(c);
                Thread.sleep(1000);
                bot.keyPress(KeyEvent.VK_CONTROL);
                bot.keyPress(KeyEvent.VK_L);
                bot.keyRelease(KeyEvent.VK_CONTROL);
                bot.keyRelease(KeyEvent.VK_L);
                full = full + String.valueOf(c);
            }
        } catch (InterruptedException e) {
            System.out.print("Error 1. Email me @ xxx@gmail.com.");
        } catch (AWTException e) {
            System.out.print("Error 2. Email me @ xxx@gmail.com.");
        }
        testSeq();
}

这是测试方法:

public void testSeq() {
        Scanner sc = new Scanner(System.in);
        System.out.print("Your attempt: ");
        user = sc.nextLine();

        if (user == null ? full == null : user.equals(full)) {
            System.out.println("Correct! Trying next combo....");
            numChars++;
            generateSeq();
        } else {
            System.out.println("Incorrect! Restarting game...");
            start();
        }
}

2 个答案:

答案 0 :(得分:2)

首先,当fullnull时,您尝试将第一个字符添加到其中。但这是字符串转换,它将null转换为String "null",而您的full变量现在以"null"开头。

首先将其初始化为空字符串""),位于generateSeq的顶部。

使用三元运算符没有任何问题,但现在字符串不会为空;他们在最糟糕的时候会是空的。单独调用equals就足够了。

if (user.equals(full))

此外,您可能希望将Random对象生成一次,作为实例变量,而不是每次调用Random时都创建新的generateSeq对象。

答案 1 :(得分:0)

代码看起来很好并且有效。
你比较它时打印包含用户和完整的内容吗?

if (user == null ? full == null : user.equals(full)) {
    System.out.println("Correct! Trying next combo....");
    numChars++;
    generateSeq();
} else {
    System.out.println("--user:" + user);
    System.out.println("--full:" + full);
    System.out.println("Incorrect! Restarting game...");
}
相关问题