Java 在没有 try-catch 的情况下验证整数或字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2485694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:17:33  来源:igfitidea点击:

Validating an integer or String without try-catch

javavalidation

提问by Phil

Ok, I'm lost. I am required to figure out how to validate an integer, but for some stupid reason, I can't use the Try-Catch method. I know this is the easiest way and so all the solutions on the internet are using it.

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

I'm writing in Java.

我正在用Java编写。

The deal is this, I need someone to put in an numerical ID and String name. If either one of the two inputs are invalid I must tell them they made a mistake.

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

Can someone help me?

有人能帮我吗?

采纳答案by Michael Aaron Safyan

If I understand you correctly, you are reading an integer or string from standard input as strings, and you want to validate that the integer is actually an integer. Perhaps the trouble you are having is that Integer.parseInt()which can be used to convert a Stringto an integer throws NumberFormatException. It sounds like your assignment has forbidden the use of exception-handling (did I understand this correctly), and so you are not permitted to use this builtin function and must implement it yourself.

如果我理解正确,您是从标准输入中读取一个整数或字符串作为字符串,并且您想验证该整数实际上是一个整数。也许您遇到的麻烦是Integer.parseInt()可用于将String转换为整数抛出NumberFormatException。听起来您的分配禁止使用异常处理(我是否正确理解这一点),因此您不得使用此内置函数,必须自己实现。

Ok. So, since this is homework, I am not going to give you the complete answer, but here is the pseudocode:

好的。所以,由于这是作业,我不会给你完整的答案,但这是伪代码:

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

The key thing here is that each digit is radix times more significant than the digit directly to its right, and so if we always multiply by the radix as we scan the string left to right, then each digit is given its proper significance. Now, if I'm mistaken, and you actually can use try-catch but simply haven't figured out how:

这里的关键是每个数字的有效基数是其右边数字的基数倍,因此如果我们在从左到右扫描字符串时总是乘以基数,那么每个数字都有其正确的意义。现在,如果我弄错了,您实际上可以使用 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
     }
}  

回答by Matthew Flaschen

Look at the hasNext methods in Scanner. Note that there are methods for each type (e.g. hasNextBigDecimal), not just hasNext.

查看Scanner中的 hasNext 方法。请注意,每种类型都有方法(例如hasNextBigDecimal),而不仅仅是 hasNext。

EDIT: No, this will not throw on invalid input, only if the Scanner is closed prematurely.

编辑:不,这不会抛出无效输入,仅当扫描器过早关闭时。

回答by coobird

Not exactly sure if the Stringthat is being validated should check whether the contents only contains numbers, or can be actually represented in the valid range of an int, one way to approach this problem is to iterate over the characters of a Stringand check that the characters are only composed of numbers.

不确定String正在验证的 是否应该检查内容是否只包含数字,或者是否可以在 an 的有效范围内实际表示,int解决此问题的一种方法是迭代 a 的字符String并检查字符是否为只由数字组成。

Since this seems to be homework, here's a little bit of pseudocode:

由于这似乎是作业,这里有一些伪代码:

define isANumber(String input):
  for (character in input):
    if (character is not a number):
      return false

  return true

回答by Laxmikanth Samudrala

Pattern p = Pattern.compile("\d{1,}");
Matcher m = p.matcher(inputStr); 
boolean isNumber = false;

if (m.find()) {
    isNumber = true;   
}

回答by Arivu2020

public static boolean IsNumeric(String s)
{
    if (s == null)
        return false;
    if (s.length() == 0)
        return false;
    for (int i = 0; i < s.length(); i++)
    {
        if (!Character.isDigit(s.charAt(i)))
            return false;
    }
    return true;
}     

回答by polygenelubricants

You can use java.util.Scannerand hasNextInt()to verify if a Stringcan be converted to an intwithout throwing an exception.

您可以使用java.util.ScannerhasNextInt()来验证是否String可以将 a 转换为 anint而不会引发异常。

As an extra feature, it can skip whitespaces, and tolerates extra garbage (which you can check for).

作为一个额外的功能,它可以跳过空格,并容忍额外的垃圾(你可以检查)。

String[] ss = {
   "1000000000000000000",
   "  -300  ",
   "3.14159",
   "a dozen",
   "99 bottles of beer",
};
for (String s : ss) {
   System.out.println(new Scanner(s).hasNextInt());
} // prints false, true, false, false, true

See also: How do I keep a scanner from throwing exceptions when the wrong type is entered?

另请参阅:当输入错误类型时,如何防止扫描仪抛出异常?

回答by Peter DeGregorio

I'm using Java 1.6 and this works for me:

我正在使用 Java 1.6,这对我有用:

if (yourStringVariable.trim().matches("^\d*$"))

then you've got a positive integer

那么你有一个正整数