java - I need this calculator to redirect the user for input incase he enters the wrong one -
in third input, asks number entered specific operation. when example "5" entered, doesn't automatically send default section display message "the value doesn't exist.". in addition that, need display input prompt again , ask number 1 through 4 entered. thx
import java.io.bufferedreader; import java.io.inputstreamreader; public class specialized { public static void main(string[] args) { string s1 = getinput("enter number: "); string s2 = getinput("enter number: "); string op = getinput("enter: 1 = add, 2 = subtract, 3 = multiply, 4 = divide "); int opint = integer.parseint(op); double result= 0; switch (opint) { case 1: result = addvalues(s1,s2); break; case 2: result = subtractvalues(s1,s2); break; case 3: result = multiplyvalues(s1,s2); break; case 4: result = dividevalue(s1,s2); break; default: system.out.println("the value doesn't exist."); break; } system.out.println(result); } private static string getinput(string prompt) { bufferedreader stdin = new bufferedreader( new inputstreamreader(system.in)); system.out.print(prompt); system.out.flush(); try { return stdin.readline(); } catch (exception e) { return "error: " + e.getmessage(); } } private static double addvalues(string s1, string s2) throws numberformatexception { double d1 = double.parsedouble(s1); double d2 = double.parsedouble(s2); double result = d1 + d2; return result; } private static double subtractvalues(string s1, string s2) { double d1 = double.parsedouble(s1); double d2 = double.parsedouble(s2); double result = d1 - d2; return result; } private static double multiplyvalues(string s1, string s2) { double d1 = double.parsedouble(s1); double d2 = double.parsedouble(s2); double result = d1 * d2; return result; } private static double dividevalue(string s1, string s2) { double d1 = double.parsedouble(s1); double d2 = double.parsedouble(s2); double result = d1 / d2; return result; } }
typically, surround "getting of input user" while
loop until desired input. this.
public static void main(string[] args) { string s1 = getinput("enter number: "); string s2 = getinput("enter number: "); //notice declare outside can compute new value inside loop int opint = 0; double result = 0; //you can change condition later if add more options while(opint < 1 || opint > 4) { string op = getinput("enter: 1 = add, 2 = subtract, 3 = multiply, 4 = divide "); //recalculate choice opint = integer.parseint(op); switch (opint) { case 1: result = addvalues(s1, s2); break; case 2: result = subtractvalues(s1, s2); break; case 3: result = multiplyvalues(s1, s2); break; case 4: result = dividevalue(s1, s2); break; default: system.out.println("the value doesn't exist."); break; } } system.out.println(result); }
Comments
Post a Comment