java - How do I make my code restart? -


so have code , inside while(mainmenu) , want learn how restart code.. using mainmenu=false; , mainmenu=true; works doesnt causing me use return crash program because user can cheat...

if(citizenlovenum<=20){             joptionpane.showmessagedialog(null, "your citizen protesting against you! need stop them before bad happens", "citizens on strike!", joptionpane.warning_message);             string strike=joptionpane.showinputdialog("choose 1 of options below! \n 1.pay them (-1000$) \n 2.send army (with move can lose 0 5 men!)", "citizens on strike!");             if(strike.equals("1")){                 if(moneycount<=0){                     joptionpane.showmessagedialog(null, "out of money! try again later..", "no money left", joptionpane.warning_message);                     return;                 }                 joptionpane.showmessagedialog(null,"the citizen's calm once more. try buying them recources won't happen again!", "citizens on strike!",joptionpane.information_message);                 moneycount-=1000;                 mainmenu=false;                 mainmenu=true;             }else{                 random army= new random();                 int armynum = army.nextint(5 - 0) + 0;                 joptionpane.showmessagedialog(null,"you have sent army. lost "+armynum+" soldiers.", "citizens on strike!",joptionpane.information_message);                 soldiercount1-=armynum;                 mainmenu=false;                 mainmenu=true;             }         } 

it works putted mainmenu=false; mainmenu=true; doesnt used return; had put return; because mainmenu=false; mainmenu=true; not working. thank time :) edit: not work when use if inside if... hope helps

from can interpret, have code this:

while(true) {     // a: stuff here      while(mainmenu) {         // b: stuff before posted code         if(citizenlovenum<=20){         // c: posted code         }     }      // d: other stuff here } 

if want go b, use continue;.

if want go d, use break;.

if need go a without touching d, enclose d in if statement.

if program ending when use continue, missing while(true) @ top. part necessary keep code running unconditionally, forever. otherwise, upon exiting while (mainmenu), program run completion.

also, add that

mainmenu = false; mainmenu = true; 

is equivalent to

mainmenu = true; 

your code executes sequentially. once inside while loop, mainmenu not checked again until encounter continue or code inside loop finishes executing.


Comments