c# - Entered wrong value. goto Start; -
edit. based on answers received realized asking more know @ stage in learning , such, have decided forget question until have learnt , understand more. not want overstep , confuse myself.
just newbie looking guidance.
from previous question asked here, introduced goto start; in switch statement.
i started using , had me thinking wanted program go start in event user entered invalid input. example, in calculator below, if user enters other number, how program disregard input , prompt user again enter number? maybe display "invalid input. please try again" user.
right now, if number entered, console crashes , throws me error.
thanks in advance assistance
int num1, num2, output; string op; console.write("\n\n"); console.writeline("calculator\n"); console.writeline("============="); console.write("\n\n"); start: console.write("please enter first number:"); num1 = convert.toint32(console.readline()); console.write("please enter second number: "); num2 = convert.toint32(console.readline()); operator: console.writeline("please select operator: "); console.writeline("\naddition : +"); console.writeline("multiplication: *"); console.writeline("division: /"); console.writeline("subtraction: -"); console.write("enter operator: "); op = console.readline(); switch (op) { case "+": output = num1 + num2; console.writeline("{0} added {1} = {2}", num1, num2, output); break; case "*": output = num1 * num2; console.writeline("{0} multiplied {1} = {2}", num1, num2, output); break; case "/": if (num2 == 0) { console.writeline("cannot divide zero. please try again"); goto start; } else { output = num1 / num2; console.writeline("{0} divided {1} = {2}", num1, num2, output); break; } case "-": output = num1 - num2; console.writeline("{0} minus{1} = {2}", num1, num2, output); break; default: console.writeline("you entered invalid operator. please try again\n"); goto operator; } console.writeline("\npress enter continue...."); console.readline();
please, whatever do, not use goto
. ever. maybe except in switch
fall down other case
, should rare. makes code unreadable, confusing , hard maintain. please see spaghetti code.
that said, should int32.tryparse
instead of convert
if not sure if input valid:
int num1; { console.write("please enter first number:"); } while (!int32.tryparse(console.readline(), out num1));
and change switch
(to avoid goto
):
bool inputok = false; while (!inputok) { console.writeline("please select operator: "); //... op = console.readline(); inputok = true; switch (op) { //... default: console.writeline("you entered invalid operator. please try again\n"); inputok = false; break; } }
Comments
Post a Comment