好吧,我迷路了。我需要弄清楚如何验证整数,但由于某些愚蠢的原因,我无法使用 Try-Catch 方法。我知道这是最简单的方法,因此互联网上的所有解决方案都在使用它。
我正在用 Java 编写。
交易是这样的,我需要有人输入数字 ID 和字符串名称。如果两个输入中的任何一个无效,我必须告诉他们他们犯了一个错误。
有人可以帮助我吗?
最佳答案
如果我没理解错的话,您正在从标准输入中读取一个整数或字符串作为字符串,并且您想要验证该整数实际上是一个整数。也许你遇到的麻烦是 Integer.parseInt()可用于转换 String到一个整数抛出 NumberFormatException .听起来您的作业禁止使用异常处理(我是否理解正确),因此您不能使用此内置函数,必须自己实现。
好的。所以,由于这是家庭作业,我不会给你完整的答案,但这是伪代码:
let result = 0 // accumulator for our result let radix = 10 // base 10 number let isneg = false // not negative as far as we are aware strip leading/trailing whitespace for the input string if the input begins with '+': remove the '+' otherwise, if the input begins with '-': remove the '-' set isneg to true for each character in the input string: if the character is not a digit: indicate failure otherwise: multiply result by the radix add the character, converted to a digit, to the result if isneg: negate the result report the result
这里的关键是每个数字的基数倍于它右边的数字,所以如果我们在从左到右扫描字符串时总是乘以基数,那么每个数字都会被赋予其正确的意义.现在,如果我弄错了,您实际上可以使用 try-catch,但只是不知道如何使用:
int result = 0; boolean done = false; while (!done){ String str = // read the input try{ result = Integer.parseInt(str); done = true; }catch(NumberFormatException the_input_string_isnt_an_integer){ // ask the user to try again } }
关于java - 在没有 try-catch 的情况下验证整数或字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2485694/