Java 返回使用“contains”比较两个字符串的结果
我输入了两个字符串,在mString中查找了子字符串。当我将该方法更改为boolean时,它通过在contains语句上使用return返回正确的true或false输出 我不知道如何使用该语句检查包含运算符的结果。我已经完成了以下工作Java 返回使用“contains”比较两个字符串的结果,java,if-statement,boolean,Java,If Statement,Boolean,我输入了两个字符串,在mString中查找了子字符串。当我将该方法更改为boolean时,它通过在contains语句上使用return返回正确的true或false输出 我不知道如何使用该语句检查包含运算符的结果。我已经完成了以下工作 public class CheckingString { public static void main(String[] args) { // adding boolean value to indicate false o
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);
}
}
}
有没有办法使check字段正常工作,以便在if-else语句中返回值
if (check = true){
应该是:
if (check == true){
通常你会写:
if(check)
查证
以及:
或:
如果!检查
检查错误。小错误:
将ifcheck=true更改为ifcheck==true或仅当选中
通过执行check=true,您将为check指定true,因此条件ifcheck=true将始终为true。在if语句中使用布尔变量的首选方法是
if (check)
请注意,您不需要使用相等运算符,这样可以避免您所犯的错误。试试看
if (check) {
System.out.println(subString + " is in " + mString);
} else {
System.out.println("No, " + subString + " is not in " + mString);
}
嗯。。。我真不敢相信我错过了。很高兴知道关于布尔的if statmenet。很常见,我马上就发现了:-很多学生都这么做。至少只在布尔人身上发生。
if (check) {
System.out.println(subString + " is in " + mString);
} else {
System.out.println("No, " + subString + " is not in " + mString);
}