【问题标题】:Returning the result of comparing two strings using 'contains'返回使用“包含”比较两个字符串的结果
【发布时间】:2012-11-21 03:38:22
【问题描述】:

所以,我输入了两个字符串,并在 mString 中查找子字符串。当我将方法更改为布尔值时,它会返回正确的输出 true 或 false(通过在 contains 语句上使用 return)。

我不知道如何使用该语句来检查包含运算符的结果。我已经完成了以下工作。

public class CheckingString
{

    public static void main(String[] args)
    {
        // adding boolean value to indicate false or true
        boolean check;

        // scanner set up and input of two Strings (mString and subString)
        Scanner scan = new Scanner(System.in);
        System.out.println("What is the long string you want to enter? ");
        String mString = scan.nextLine();
        System.out.println("What is the short string that will be looked for in the long string? ");
        String subString = scan.nextLine();

        // using the 'contain' operator to move check to false or positive.
        // used toLowerCase to remove false negatives
        check = mString.toLowerCase().contains(subString.toLowerCase());

        // if statement to reveal resutls to user
        if (check = true)
        {
            System.out.println(subString + " is in " + mString);
        }
        else
        {
            System.out.println("No, " + subString + " is not in " + mString);
        }
    }

}

有没有办法使该检查字段正常工作以在 if-else 语句中返回一个值?

【问题讨论】:

    标签: java if-statement boolean


    【解决方案1】:
    if (check = true){
    

    应该是:

    if (check == true){
    

    通常你会写:

    if(check)
    

    检查真假

    和:

    if(!(check)) 
    

    或:

    如果(!检查)

    检查是否为假。

    【讨论】:

    • Doh... 我不敢相信我错过了。也很高兴了解布尔 if-statmenet。
    • 很常见,我马上就发现了 :-)(很多学生都这样做)。至少只发生在布尔值上。
    【解决方案2】:

    小错误:

    if(check = true) 更改为if(check == true) 或只是if (check)

    通过执行check = true,您将分配true 进行检查,因此条件if(check = true) 将始终为true。

    【讨论】:

      【解决方案3】:

      在 if 语句中使用布尔变量的首选方法是

      if (check)
      

      请注意,您不需要使用相等运算符,这样可以避免您犯的错误。

      【讨论】:

        【解决方案4】:

        试试看

         if (check) {
                System.out.println(subString + " is in " + mString);
            } else {
                System.out.println("No, " + subString + " is not in " + mString);
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-06-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多