2012-11-21 73 views
0

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

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

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语句中的值?

回答

5
if (check = true){ 

应该是:

if (check == true){ 

通常你会写:

if(check) 

检查真正

和:

if(!(check)) 

或:

如果(!检查)

来检查错误。

+0

卫生署...我无法相信我错过了。很高兴知道布尔if-statmenet。 – user1588867

+0

足够常见,我马上发现它:-)(很多学生都这么做)。至少只有布尔值才会发生。 – TofuBeer

5

琐碎的错误:

变化if(check = true)if(check == true)或只是if (check)

check = true要指定真正检查这样的条件if(check = true)永远是正确的。

0

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

if (check) 

请注意,您不需要使用相等运算符,它避免了出现错误的位置。

0

试试吧

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