Java - 检查parseInt是否抛出异常 [英] Java - checking if parseInt throws exception

查看:134
本文介绍了Java - 检查parseInt是否抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果Integer.parseInt(无论如何)没有失败,该如何做某事。

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

更具体地说,我有一个用户指定值的jTextArea分离按换行符。

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

我想检查每一行,看看是否可以转换为int。

I want to check each line to see if can be converted to an int.

想象这样,但它不起作用:

Figured something like this, but it doesn't work:

for(int i = 0; i < worlds.jTextArea1.getLineCount(); i++){
                    if(Integer.parseInt(worlds.jTextArea1.getText(worlds.jTextArea1.getLineStartOffset(i),worlds.jTextArea1.getLineEndOffset(i)) != (null))){}
 }

感谢任何帮助。

推荐答案

public static boolean isParsable(String input){
    boolean parsable = true;
    try{
        Integer.parseInt(input);
    }catch(ParseException e){
        parsable = false;
    }
    return parsable;
}

请记住,我将ParseException视为特定类型的特定异常案例

keep in mind that I meant ParseException as the proper type of exception for the specific case

这篇关于Java - 检查parseInt是否抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆