【问题标题】:Java If loop don't get executed: Scanner [duplicate]Java If循环没有被执行:扫描仪[重复]
【发布时间】:2013-06-09 17:36:36
【问题描述】:

我的第二个扫描仪输入按需要存储,但仍然没有执行比较正确字符串 == stringValue 的 if 条件。 你能帮忙吗?

{

static String stringValue = "A";
public static void main(String[] args) {
    int time;
    time = speedType();
    //System.out.println(time);
}
private static int speedType() {
    System.out.println("Let's play a game\nHow fast can you type \"I type very quickly\" \nPress Enter then type the statement and then press Enter again");
    Scanner scanner = new Scanner (System.in);
    String string = scanner.nextLine();
    if(string.equals("")){
        Date startTime = new Date();
        System.out.println("Start:\n");
        String correctString = scanner.nextLine();
        System.out.println(correctString);
        if (correctString == stringValue){
            Date endTime = new Date();
            System.out.println(endTime);
        }
        else
            System.out.println("Please enter correct string");
    }
    return 0;       



}}

【问题讨论】:

  • 你在这里做对了string.equals("")在这里做错了if (correctString == stringValue){...
  • 今天是==的国庆日吗?
  • @MarounMaroun 它是所有的日子......
  • 他们应该让 == 在 java9 中的字符串上做 .equals。

标签: java loops if-statement java.util.scanner


【解决方案1】:

关于,

if (correctString == stringValue){

不要使用== 比较字符串。请改用equals(...)equalsIgnoreCase(...) 方法。了解== 检查两个 objects 是否相同,这不是您现在感兴趣的。另一方面,这些方法检查两个字符串是否以相同的顺序具有相同的字符,这就是这里的重点。所以不是

if (fu == "bar") {
  // do something
}

做,

if ("bar".equals(fu)) {
  // do something
}

或者,

if ("bar".equalsIgnoreCase(fu)) {
  // do something
}

【讨论】:

  • 哦,真快。几乎就像谷歌搜索一样......是的,它奏效了。我理解你所说的。谢谢:)
  • @CtrlV:不客气。我在一个文本文件中有这个答案以及其他股票答案,因为它经常被问到。
  • @CtrlV 我只是想知道你为什么在 if(string.equals("")) 中使用 equals 而不是在 if (correctString == stringValue) 中使用 :)
猜你喜欢
  • 2018-05-03
  • 1970-01-01
  • 2019-11-28
  • 1970-01-01
  • 2016-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-06
相关资源
最近更新 更多