Java boolean conditioned while loop seemingly ignoring an if statement? -



Java boolean conditioned while loop seemingly ignoring an if statement? -

around here - if (code<10 || code>99) seems issue. when entering number outside range loop continues infinitely, seemingly ignoring condition. tried system.exit(0), though did job seek , utilize while loop stop code.

import java.util.*; public class lockpicker { public static void main(string[] args) { scanner kb = new scanner(system.in); random r = new random(); boolean stop = false; while (!stop) { system.out.print("what unlock code? "); int code = kb.nextint(); if (code<10 || code>99) { system.out.println("your number must between 10 , 99"); stop = !stop; } system.out.println("picking lock..."); system.out.println(""); int x = -1, counter = 0; while (x!=code) { x = r.nextint(90)+10; system.out.println(x); counter++; } system.out.println("that took "+counter+" tries pick lock!"); stop = !stop; } } }

you don't need stop variable. can utilize break , continue.

random r = new random(); while (true) { system.out.print("what unlock code? "); int code = kb.nextint(); if (code < 10 || code > 99) { system.out.println("your number must between 10 , 99"); continue; } system.out.println("picking lock..."); system.out.println(""); int x = -1, counter = 0; while (x != code) { x = r.nextint(90) + 10; system.out.println(x); counter++; } system.out.println("that took " + counter + " tries pick lock!"); break; }

continue skip iteration , go while loop prompt user 1 time again number. break end while loop when match found.

java loops while-loop

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -