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

73 Views Asked by At
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;
     }
 }

this program is looking for checking the char is in the string or not.

Hello, E = true
Hello, a = false

3

There are 3 best solutions below

3
On BEST ANSWER

In this method test1, your forloop will traverse the whole line although it finds the letter into the string. so update it like this:

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;
     }

Because, if the letter is found into the string you don't need to check further, hence:

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

Note that, return statement causes execution to leave the current function or tersely current subordinate.

0
On

You're never breaking out of the loop. Consider "Hello" and 'e'

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

break from the loop. Or, just use String.indexOf(char)

4
On

after each check you are changing result, without considering the option the the character is already found. you can see is in twentylemon's answer.

i just wanted to say something that will be more correct and efficient. insted of using break and return result you can do return true if the character is found. in the end of the loop return false.

in this way, you dont need the result variable and the break.

this is how you write it as i suggested:

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;
 }

if you will check it, you will see how simple and good it is :)