Java - checking if parseInt throws exception

后端 未结 8 1235
清歌不尽
清歌不尽 2020-12-06 09:17

I\'m wondering how to do something only if Integer.parseInt(whatever) doesn\'t fail.

More specifically I have a jTextArea of user specified values seperated by line

相关标签:
8条回答
  • 2020-12-06 09:30

    It would be something like this.

    String text = textArea.getText();
    Scanner reader = new Scanner(text).useDelimiter("\n");
    while(reader.hasNext())
        String line = reader.next();
    
        try{
            Integer.parseInt(line);
            //it worked
        }
        catch(NumberFormatException e){
           //it failed
        }
    }
    
    0 讨论(0)
  • 2020-12-06 09:32
    public static boolean isParsable(String input) {
        try {
            Integer.parseInt(input);
            return true;
        } catch (final NumberFormatException e) {
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 09:38

    parseInt will throw NumberFormatException if it cannot parse the integer. So doing this will answer your question

    try{
    Integer.parseInt(....)
    }catch(NumberFormatException e){
    //couldn't parse
    }
    
    0 讨论(0)
  • 2020-12-06 09:38

    instead of trying & catching expressions.. its better to run regex on the string to ensure that it is a valid number..

    0 讨论(0)
  • 2020-12-06 09:44

    You can use a scanner instead of try-catch:

    Scanner scanner = new Scanner(line).useDelimiter("\n");
    if(scanner.hasNextInt()){
        System.out.println("yes, it's an int");
    }
    
    0 讨论(0)
  • 2020-12-06 09:54

    Check if it is integer parseable

    public boolean isInteger(String string) {
        try {
            Integer.valueOf(string);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
    

    or use Scanner

    Scanner scanner = new Scanner("Test string: 12.3 dog 12345 cat 1.2E-3");
    
    while (scanner.hasNext()) {
        if (scanner.hasNextDouble()) {
            Double doubleValue = scanner.nextDouble();
        } else {
            String stringValue = scanner.next();
        }
    }
    

    or use Regular Expression like

    private static Pattern doublePattern = Pattern.compile("-?\\d+(\\.\\d*)?");
    
    public boolean isDouble(String string) {
        return doublePattern.matcher(string).matches();
    }
    
    0 讨论(0)
提交回复
热议问题