java - Why "if" is not doing anything in this boolean method? -
import java.util.scanner;//import scanner public class review{ //name of program public static void main(string[]args){ // main statement scanner i=new scanner(system.in); system.out.println("enter string"); string b=i.nextline(); system.out.println("enter letter"); char c=i.next().charat(0); system.out.println("answer "+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 looking checking char in string or not.
hello, e = true
hello, = false
in method test1
, for
loop traverse whole line although finds letter
string
. update 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 letter
found string
don't need check further, hence:
if(a.charat(i)==b) // if condition finds true path return true; // return true
note that, return
statement causes execution leave current function
or tersely current subordinate.
Comments
Post a Comment