2013-01-08 194 views
40

我有一个gpa程序,它可以与equalsIgnoreCase()方法一起使用,它比较两个字符串,字母“a”给用户输入,它检查是否将“a”与否。但是现在我想添加一个异常,并在数字是输入时执行错误消息。我希望程序认识到整数输入与字符串不同,并给出错误消息。我可以用哪种方法比较一个类型字符串变量输入类型int,并抛出异常?如何检查一个字符串是否是数字?

+6

'Pattern.compile( “[0-9] +”)匹配(串)',也许? –

+0

那么你想匹配*只*整数或任何数字? – arshajii

+0

我不想让他们输入任何数字基本上,只是字符串 – user1944277

回答

5

以下方法使用,

public static boolean isNumeric(String str) 
{ 
    try 
    { 
    double d = Double.parseDouble(str); 
    } 
    catch(NumberFormatException nfe) 
    { 
    return false; 
    } 
    return true; 
} 

如果你想使用正则表达式,你可以按照以下使用,

public static boolean isNumeric(String str) 
{ 
    return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal. 
} 
+1

尝试和捕捉excpetion有这么大的开销,虽然。 – WorldSEnder

+0

异常编码是一种已知的反模式。 请参阅https://en.wikipedia.org/wiki/Coding_by_exception和https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if -so-why – mcalmeida

61

许多选项探讨在http://www.coderanch.com/t/405258/java/java/String-IsNumeric

还有一个是

public boolean isNumeric(String s) { 
    return s != null && s.matches("[-+]?\\d*\\.?\\d+"); 
} 

可能会过度杀伤,但Apache Commons NumberUtils似乎也有一些帮手。

+1

我会将最后一个“+”更改为“*”,以使得“123.”变为有效输入(小数分隔符后的任何内容都是有效输入) – peterh

+2

我会为NULL添加检查...否则它会崩溃 –

0

下面介绍如何检查输入包含一个数字:

if (input.matches(".*\\d.*")) { 
    // there's a digit somewhere in the input string 
} 
+0

嘿,谢谢,这有帮助,但m程序仍然在异常抛出后终止。如果我拿出例外,它会完美运行......就像我要求的那样,即使是一个数字。任何关于如何仍然保持prgm在我跳过异常后继续运行的想法 – user1944277

+0

将代码投掷到try-catch中的代码,捕获抛出的异常。 – Bohemian

+0

我已经试过只是包装我的整个代码部分提示输入尝试赶上,但它没有奏效,你可以澄清使用我上面发布的代码 – user1944277

30

如果你被允许使用第三方库,建议如下。

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html

NumberUtils.isDigits(str:String):boolean 
NumberUtils.isNumber(str:String):boolean 
+2

你不需要任何第三方:loop:if(Character.isDigit(c)) –

+3

请注意! isNumeric,isDigits只处理纯数字。即他们将返回虚假的7,574。 (以逗号分隔的数字)。 –

+0

isNumber(str:String)is Deprecated –

4

使用此

public static boolean isNum(String strNum) { 
    boolean ret = true; 
    try { 

     Double.parseDouble(strNum); 

    }catch (NumberFormatException e) { 
     ret = false; 
    } 
    return ret; 
} 
+1

试图捕获其他异常也:) 如果你发送了一个'Null'对象字符串,这就失败了 – prime

3
public static boolean isNumeric(String string) { 
    if (string == null || string.isEmpty()) { 
     return false; 
    } 
    int i = 0; 
    int stringLength = string.length(); 
    if (string.charAt(0) == '-') { 
     if (stringLength > 1) { 
      i++; 
     } else { 
      return false; 
     } 
    } 
    if (!Character.isDigit(string.charAt(i)) 
      || !Character.isDigit(string.charAt(stringLength - 1))) { 
     return false; 
    } 
    i++; 
    stringLength--; 
    if (i >= stringLength) { 
     return true; 
    } 
    for (; i < stringLength; i++) { 
     if (!Character.isDigit(string.charAt(i)) 
       && string.charAt(i) != '.') { 
      return false; 
     } 
    } 
    return true; 
} 
6
+5

为什么会投票? – Rudi

+0

我没有投票给你,但你不需要添加更多的软件。在Java SE中:loop:if(Character.isDigit(c)) –

+2

请注意! isNumeric只处理纯数字。即,它将返回虚假的7,574。 (以逗号分隔的数字)。 –

0

要检查所有的诠释字符,你可以简单地使用双重否定。如果(!searchString.matches(“[^ 0-9] + $”))...

[^ 0-9] + $检查是否有任何字符不是整数,所以测试失败,如果它是真的。只是没有,你会成功。

0

您可以使用Character.isDigit(char ch)方法,或者也可以使用正则表达式。

下面是摘录:

public class CheckDigit { 

private static Scanner input; 

public static void main(String[] args) { 

    System.out.print("Enter a String:"); 
    input = new Scanner(System.in); 
    String str = input.nextLine(); 

    if (CheckString(str)) { 
     System.out.println(str + " is numeric"); 
    } else { 
     System.out.println(str +" is not numeric"); 
    } 
} 

public static boolean CheckString(String str) { 
    for (char c : str.toCharArray()) { 
     if (!Character.isDigit(c)) 
      return false; 
    } 
    return true; 
} 

}

0

我最后在我的程序写了这个小方法,所以我可以检查一个字符串是否是数字或至少每一个字符是一个数字。

private boolean isNumber(String text){ 
    if(text != null || !text.equals("")) { 
     char[] characters = text.toCharArray(); 
     for (int i = 0; i < text.length(); i++) { 
      if (characters[i] < 48 || characters[i] > 57) 
       return false; 
     } 
    } 
    return true; 
} 
4

简单方法:

public boolean isBlank(String value) { 
    return (value == null || value.equals("") || value.equals("null") || value.trim().equals("")); 
} 


public boolean isOnlyNumber(String value) { 
    boolean ret = false; 
    if (!isBlank(value)) { 
     ret = value.matches("^[0-9]+$"); 
    } 
    return ret; 
} 
相关问题