c# - Test Console.ReadLine(); input type -
i'm making console app in i'll ask user phone number int main_phone
, if types string thats not convertible int such "caramel" want give him warning , ask number.
well thought recursive function do, i'm lacking logical aptitude one. came following code snippet:
static int? tryparse(string str) { int tmp; if (int.tryparse(str, out tmp)) { return tmp; } return null; }//end of tryparse(); static int? verifyparse(string str, string lable) { int? testedvar = tryparse(str); if (testedvar == null) { console.writeline("este campo pode apenas conter dígitos de 0 à 9."); console.write(lable); verifyparse(console.readline(), lable); return null; } else { return testedvar; } }//end of verifyparse(); console.write("phone(main):"); int? main_phone = verifyparse(console.readline(),"telefone (principal):");
the problem if user inputs "string" main_phone comeback null, asks number between 0 , 9, if user passes convertible string , such "12", main_phone still null.
how can fix that?
edit 1:
what need function if string can converted int returns int, else gives me error , asks me input between 0 , 9. find hard because function have able return int or run self on again(to require , test valid input), can't because either returns int or doesn't return nothing.
edit 2:
here little update on problem:
static int tryparse(string lable) { string str = console.readline(); regex regex = new regex(@"\d+"); while (!regex.ismatch(str)) { console.writeline("insira apenas dígitos de 0-9, por favor."); console.write(lable); str = console.readline(); } return convert.toint32(str); }//end of tryparse(); console.write("telefone (principal):"); int main_phone = tryparse("telefone (principal):");
works well, except when input "1a". in case i'll error:
system.formatexception: input string not in correct format. @ system.number.stringtonumber(string str, numberstyles options, numberbuffer& number, numberformatinfo info, boolean parsedecimal) @ system.number.parseint32(string s, numberstyles style, numberformatinfo info) @ system.convert.toint32(string value) @ app1.program.tryparse(string lable) @ app1.program.main(string[] args)
here's solution loops until match produced, using regex validation
regex regex = new regex(@"\d{3}-?\d{3}-?\d{4}"); string phonenumber = console.readline(); while (!regex.ismatch(phonenumber)) { console.writeline("bad input"); phonenumber = console.readline(); } return convert.toint32(phonenumber.replace("-",""));
which match 5555555555 , 555-555-5555, , return int value.
Comments
Post a Comment