Java If (conditions) are NOT TRUE 用于抛出异常的语法

Java If (conditions) are NOT TRUE syntax for throwing Exception

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

如果 (condition1 || condition2) 为假 { 抛出异常}

    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."); }

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

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

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

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

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