Java - Given an int array print true if it contains 2 or 3 -
im dooing java1001 course, not doing object oriented programming. i'm having trouble figuring out problem regarding array.
given int array, print true if contains 2 or 3. // {2, 5} -> true // {4, 3} -> true // {4, 5} -> false //
scanner keyboard = new scanner(system.in); int size = keyboard.nextint(); int[] = new int[size]; for(int = 0 ;i<a.length;i++) a[i] = keyboard.nextint(); for(int = 0 ;i<a.length;i++) if(a[i] == 2 || a[i] == 3) system.out.println(true); else system.out.println(false);
when tested yields "truefalse", "falsetrue" , "falsefalse" how can make stop examining entire array if first integer yields true ?
any 1 can me?
thanks in advance :)
you can start using break
keyword, although won't fix issue.
if(a[i] == 2 || a[i] == 3) { system.out.println(true); break; }
break do?
break stops it's doing in loop. if you're cycling through for loop
, don't need cycle more, use break
keyword, , stop loop.
how work in instance?
as loop hits 2
or 3
, it's going print out true
. hit break
, , loop ends.
if hits anyhting else, move else
, , print false
. this, however, not desired, we're going little differently. here pseudo-code:
boolean b = false; for( 0 size) { if 2 or 3 b = true; break; } // print result. system.out.println(b);
Comments
Post a Comment