Java true 如果以 结尾


public boolean endsLy(String str) {
      if(str.length() < 2){
          return false;
      }else if(str.substring(str.length()-2, str.length())).equals("ly){
          return true;
      }else{
          return false;}
}

所以这是一个简单的问题,如果以"ly"结尾,则返回 true。我尝试这样做,但我遇到了一些错误。(在 else 下,和等于(。我今天一直在学习所有这些。任何帮助表示赞赏:D

从您的版本中,您只有几个错别字

public boolean endsLy(String str) 
{
    if(str.length() < 2)
        return false;
    else if(str.substring(str.length() - 3, str.length()).equals("ly"))
        return true;
    else
        return false;
}

但是,如果我写了一个程序来测试这一点,我会这样写:

public boolean endsLy(String str) 
{
    // If string doesn't end with ly, is null, or has a length of zero
    if(str == null || str.length() == 0 || !str.endsWith("ly"))
        return false;
    return true;
}

括号是什么样子的(我的首选版本(

public boolean endsLy(String str) 
{
    if(str.length() < 2)
    {
        return false;
    }
    else if(str.substring(str.length() - 3, str.length()).equals("ly"))
    {
        return true;
    }
    else
    {
        return false;
    }
}
/*
^   ^ all the brackets line up, which for me makes readability a breeze
|   | */

另一种方式,你通常会看到它的格式(不是我的首选方式,但通常是行业标准,减少了代码中的行数(。

public boolean endsLy(String str) 
{
    if(str.length() < 2) {
        return false;
    }
    else if(str.substring(str.length() - 3, str.length()).equals("ly")) {
        return true;
    }
    else {
        return false;
    }
}

相关内容

最新更新