2017-01-31 42 views
1

后重试方法。当文本的输入在此方法中的Java Swing是不例外

private int random1DimGetNumeral(String textThatCausesError){ 
    int result = 2; 
    try{ 
     result = Integer.parseInt(textThatCausesError); 
    } catch (Exception inputError) { 
     textPanel.setText("Input Error for Random Dimmension feild 1.\n"); 
    } 
    return result; 
} 

的参数textThatCausesError给出,后来当文本是数字,防爆“56”。它仍然捕获异常并返回2。我的捕获是否过于通用?

+2

Integer.parseInt(textThatCausesError);是正确的...你肯定已经尝试了另一个值! –

+1

只是一个猜测:你有检查56前后的空格吗?例如。 “56”或“56”。尝试'Integer.parseInt(textThatCausesError.trim())'。 – Rick

+1

你的捕获过于宽泛('Exception'),你应该把它缩小到更具体的一个(在这种情况下'NumberFormatException')。但是,这不是你的代码的问题。唯一可能发生的事情是你的字符串不能作为整数进行分析。 [ΦXocę웃Пepeúpaツ](http://stackoverflow.com/users/982161/%ce%a6xoc%c4%99-%ec%9b%83-%d0%9fepe%c3%bapa-%e3%83%84 )在[他的回答](http://stackoverflow.com/a/41955933/507738)中列举了可能的原因。 –

回答

2

Integer.parseInt(textThatCausesError);是正确的,唯一的选择得到一个例外是:

  • 你试图用字符串 未表示整数
  • 或者您正在用串号,在满溢在尝试解析后的整型容量(32位)
1

这对我有用。

class Pong { 
    public static void main(String[] args){ 
     Pong pong = new Pong(); 
     System.out.println(pong.random1DimGetNumeral("56")); 
    } 

    private int random1DimGetNumeral(String textThatCausesError){ 
     int result = 2; 
     try{ 
      result = Integer.parseInt(textThatCausesError); 
     } catch (Exception inputError) { 
      System.out.println("Input Error for Random Dimmension feild 1.\n"); 
     } 
     return result; 
    } 
}