Reset variables back to zero in do-while loop Java -
i working on example using do-while loop , switch statement. need accumulate numbers , depending on user input either add, substract, multiply or divide (mini calculator type).
the problem when ask user go main menu program not reset value before loop. result previous result.
here code, explain better.
import java.util.scanner; public class switchloopnumbers{ public static void main(string[] args){ scanner scan = new scanner(system.in); int numbers=0; int result=0; int option; boolean quit = true; string done=""; do{ system.out.println("calculator menu"); system.out.println("********** ****"); system.out.println("\n1. add"); system.out.println("2. substract"); system.out.println("3. multiply"); system.out.println("4. divide"); system.out.println(); system.out.print("enter option >> "); option = scan.nextint(); while(quit){ switch(option){ case 1: system.out.print("enter numbers, type 0 when done >> "); numbers = scan.nextint(); if(numbers==0) quit=false; result +=numbers; break; case 2: system.out.print("enter numbers, type 0 when done >> "); numbers = scan.nextint(); result -=numbers; if(numbers==0) quit=false; break; } } system.out.println("the total is: "+result); system.out.println("back main menu ? y/n "); scan.nextline(); done = scan.nextline(); //i did reset numbers , result here 0 did not work } while("y".equalsignorecase(done)); system.out.println("thank using calculator"); } }
a couple things going on here. answer question concisely, it's because didn't reassign variables before re-looping. since don't reassign result , quit, quit false closes loop, , result unchanged prints same result. try this:
system.out.println("the total is: "+result); system.out.println("back main menu ? y/n "); scan.nextline(); done = scan.nextline(); numbers = 0; result = 0; quit = true;
i think it's straight-forward solution problem.
edit: wanted add using quit while condition seems little counter-intuitive. if saw condition quit true, assumption would break loop, not continue it. might make code bit clearer designating more meaningful variable names. instead of saying like:
boolean quit = true; while(quit) { //do stuff if (some_condition) { quit = false; //close loop } }
this may little clearer:
boolean quit = false; while(!quit) { //do stuff if (some_condition) { quit = true; //close loop } }
just general suggestion.
Comments
Post a Comment