【问题标题】:Java: What is the equivalent of != when comparing strings?Java:比较字符串时 != 的等价物是什么?
【发布时间】:2015-12-05 02:25:16
【问题描述】:

我希望当用户在忽略大小写时输入“停止”或“继续”以外的值时执行 while 循环。我怎样才能做到这一点?每当我运行程序时,即使我输入继续或停止,它也会打印“无效条目”。我究竟做错了什么?

package butt;

    import java.util.*; // used for console input

    public class butt_face{

    static Scanner console = new Scanner(System.in); // needed for user input

    public static void main(String[] args) {

   String strContinue; // input from console and used for boolean

    System.out.println("Would you like to stop or continue? ");
    strContinue = console.next();
    while(!(strContinue.equalsIgnoreCase("stop")) || !(strContinue.equalsIgnoreCase("continue")))
        {   
            System.out.println("Invalid entry");
            System.out.println("Would you like to stop or continue? ");
            strContinue = console.next();
        } // end while
    if(strContinue.equalsIgnoreCase("stop")
    {
        System.out.println("Good bye!");
    } // end if
    else
        System.out.println("Poop Ship Destroyer");

    } // end of main

    } // end of class

【问题讨论】:

  • 你能再具体一点吗?
  • 更具体?他为你写了代码。看看它并思考。
  • if(!someString.equals(otherString))
  • @duffymo !str.equals() 不忽略大小写
  • 你应该看看一些关于形式逻辑的教程来帮助你的控制语句。

标签: java string boolean


【解决方案1】:

你有错误的运算符:

!(strContinue.equalsIgnoreCase("stop"))

true,除非strContinue"stop"

!(strContinue.equalsIgnoreCase("continue"))

true,除非strContinue"continue"

strContinue 不能同时是"stop""continue",因此至少有一个条件将始终为true,而false || truetrue

解决方案:将 or (||) 更改为 and (&&)。

【讨论】:

  • @Boognish 如果您发现此答案有用,请随时点赞并接受!
【解决方案2】:

您需要在条件中替换为 && 而不是 || 检查repl https://repl.it/B6GJ/0

【讨论】:

    【解决方案3】:

    问题在于你的逻辑。

      while(!(strContinue.equalsIgnoreCase("stop")) || !   (strContinue.equalsIgnoreCase("continue")))
    

    这部分检查strContinue是否等于stop,如果等于stop,它将检查strContinue是否等于continue。

    【讨论】:

      【解决方案4】:

      执行类似输入函数的操作,调用输入扫描器,直到您输入这两个字符串之一。

      【讨论】:

      • 为什么要调用函数来简单地比较两个字符串?
      • 我真的不明白他的意思,因为他使用了一个特殊的 equals 变体,并一直要求通用一个!所以我只是想推荐他将他的代码外包到一个输入法中,该输入法会一直运行直到得到想要的结果,这样他就可以在任何地方重复使用它。
      • 好吧,他的(即 OP 的)“观点”是没有根据的,真的。但是>>真正的重点
      猜你喜欢
      • 2010-12-25
      • 1970-01-01
      • 2020-06-03
      • 1970-01-01
      • 2015-02-23
      • 2016-06-10
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      相关资源
      最近更新 更多