Java Loops - Break? Continue? -
i've read through bunch of threads on using break
, continue
, suspect problem isn't use of those, layout of loops. in following code, trying iterate through chars in string input user find -
symbols. if found, throw error user negative number found , exit. otherwise, if not find -
symbol, should print out of chars in string.
i used break
@ end of first loop find -
symbol, not continuing on next loop. tried continue
didn't work. loops new me may have wrong, know first loop working ok , throw error when finds -
in string.
strnum1 = joptionpane.showinputdialog ("enter number string"); (int = 0; < strnum1.length(); i++) { char c = strnum1.charat(i); if (c == '-') { system.out.println("negative digit found - exiting"); break; } } (int = 0; < strnum1.length(); i++) { char c = strnum1.charat(i); if (c <= 9) { system.out.println(c); } }
the break statement breaks first loop. in order skip running second loop in event of finding -
character, can use boolean
variable indicate whether second loop should run :
strnum1 = joptionpane.showinputdialog ("enter number string"); boolean isvalid = true; (int i=0; i<strnum1.length(); i++) { char c = strnum1.charat(i); if (c == '-'){ system.out.println("negative digit found - exiting"); isvalid = false; break; } } if (isvalid) { (int i=0; i<strnum1.length(); i++) { char c = strnum1.charat(i); if (c <= '9'){ system.out.println(c); } } }
Comments
Post a Comment