验证没有try-catch的整数或字符串

Phi*_*hil 1 java validation

好的,我迷路了.我需要弄清楚如何验证整数,但由于一些愚蠢的原因,我不能使用Try-Catch方法.我知道这是最简单的方法,所以互联网上的所有解决方案都在使用它.

我正在用Java写作.

这个交易是这样的,我需要有人输入数字ID和字符串名称.如果两个输入中的任何一个无效,我必须告诉他们他们犯了错误.

有人能帮我吗?

Mic*_*yan 5

如果我理解正确,您将从标准输入读取整数或字符串作为字符串,并且您要验证整数实际上是整数.也许你遇到的麻烦是可以用来将String转换为整数的Integer.parseInt()抛出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
     }
}