为什么 "if" 在这个布尔方法中没有做任何事情?

Why "if" is not doing anything in this boolean method?

import java.util.Scanner;//import Scanner
public class review{ //name of the program
    public static void main(String[]args){ // main statement
        Scanner i=new Scanner(System.in);
        System.out.println("Enter a string");
        String b=i.nextLine();

        System.out.println("Enter a letter");
        char c=i.next().charAt(0);
        System.out.println("Answer is "+test1(b,c));
    }
     public static boolean test1(String a, char b){
         boolean result= true;
         for(int i=0;i<a.length();i++)
             if(a.charAt(i)==b)
                 result =true;
             else
                 result=false;
         return result;
     }
 }

此程序正在检查字符是否在字符串中。

Hello, E = true
Hello, a = false

你永远不会跳出循环。考虑 "Hello"'e'

 see H: result = false
 see e: result = true
 see l: result = false...

break 来自循环。或者,只需使用 String.indexOf(char)

在这种方法 test1 中,您的 for 循环将遍历整行,尽管它发现 letter 进入 string。所以像这样更新它:

public static boolean test1(String a, char b){
         for(int i=0;i<a.length();i++) {
             if(a.charAt(i)==b)
                 return true;
         }
         return false;
     }

因为,如果 letterstring 中找到,则不需要进一步检查,因此:

if(a.charAt(i)==b) // if condition finds true path
    return true; // so return true

请注意,return 语句会导致执行离开当前 function 或简短的当前下属。

每次检查后你都会改变结果,而不考虑已经找到字符的选项。 你可以看到在 .

我只是想说一些更正确和有效的东西。 代替使用 break 和 return result 如果找到该字符,您可以执行 return true。 在循环结束时 return false.

这样就不需要result变量和break了。

这是你按照我的建议写的:

public static boolean test1(String a, char b)
{
     for(int i=0;i<a.length();i++)
     {
         if(a.charAt(i)==b)
         {
             return true;
         }
     }
     return false;
 }

如果你检查一下,你会发现它是多么简单和好:)