Java字符串比较总是返回false
我正在用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();
}
}
# 1 楼答案
在开头,当},而
full
为null
时,尝试向其添加第一个字符。但这是字符串转换,它将null
转换为String
{full
变量现在以"null"
开头首先将其初始化为空字符串(
""
),位于generateSeq
的顶部使用三元运算符没有问题,但现在字符串不会为null;最糟糕的情况是它们是空的。现在,单独调用
equals
就足够了此外,您可能希望生成一次
Random
对象作为实例变量,而不是每次调用generateSeq
时都创建一个新的Random
对象# 2 楼答案
代码看起来很好,而且有效
比较时是否打印包含用户和完整信息的内容