【问题标题】:Java If (conditions) are NOT TRUE syntax for throwing ExceptionJava If (conditions) are NOT TRUE 抛出异常的语法
【发布时间】:2021-05-11 00:58:40
【问题描述】:

我正在尝试为此项目使用异常块,如果子字符串与“标题”或“作者”不匹配,则需要引发异常。我想使用 if (condition) is false 语句来抛出我的异常,但我知道对于字符串我无法与 != 进行比较,因为运算符比较的是地址而不是内容。

如果 (condition1 || condition2 ) is false { 抛出异常}

    public String getLongest(String property) throws IllegalNovelPropertyException{
       String longest = "";
      if (property.equalsIgnoreCase("author" ) || property.equalsIgnoreCase("title" ) is false);
       {
           throw new IllegalNovelPropertyException("Bad property. Substring must be title or author."); }

【问题讨论】:

  • if (!(condition1 || condition2 ))

标签: java exception syntax


【解决方案1】:

用Java写is false的正确方法是使用否定!。您的代码将变为:

if(!(property.equalsIgnoreCase("author") || property.equalsIgnoreCase("title"))) {
    // Code.
}

或者,您可以将该逻辑重写为以下等效项(根据偏好):

if(!property.equalsIgnoreCase("author") && !property.equalsIgnoreCase("title")) {
    // Code.
}

编辑:请注意,您在 if(); {} 中使用了分号 (;),而 Java 中的语法是 if() {},没有分号。

【讨论】:

    猜你喜欢
    • 2014-06-25
    • 2019-08-08
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    相关资源
    最近更新 更多