我的java编码与数字和字符串有问题

时间:2015-01-25 20:43:55

标签: java if-statement error-handling integer double

我尝试使用netbeans开发一个java程序,其中GUI接受来自五个文本字段的主题标记,并在各自的文本字段中显示总标记,百分比和等级。 问题是我在执行GUI时遇到错误。我尝试用double替换int来保存百分比的百分比,但这没有帮助。我无法找到任何错误,因为我是初学者,我无法理解我的netbeans在监视器中给出的错误。请帮忙。

ERRORS: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "           34"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:481)
    at java.lang.Integer.parseInt(Integer.java:527)
    at NewJFrame.submit_buttonActionPerformed(NewJFrame.java:173)
    at NewJFrame.access$000(NewJFrame.java:4)
    at NewJFrame$1.actionPerformed(NewJFrame.java:60)

这是我完成的编码。

        int sub1_ = Integer.parseInt(sub1.getText());
    int sub2_ = Integer.parseInt(sub2.getText());
    int sub3_ = Integer.parseInt(sub3.getText());
    int sub4_ = Integer.parseInt(sub4.getText());
    int sub5_ = Integer.parseInt(sub5.getText());

    // Here each subject holds a max. of 100 marks.

    int a = sub1_+sub2_+sub3_+sub4_+sub5_;
    total_marks.setText(""+a);

    // Since each subject holds a max. of 100 marks, the total marks of five subjects sums up to 500.

    int b = (a/500)*100;
    percentage.setText(b+"%");

    if(b<=100&&b>=91)
    {grade.setText("A1");}

    else if(b<=90&&b>=81)
    {grade.setText("A2");}

    else if(b<=80&&b>=71)
    {grade.setText("B1");}

    else if(b<=70&&b>=61)
    {grade.setText("B2");}

    else if(b<=60&&b>=51)
    {grade.setText("C1");}

    else if(b<=50&&b>=35)
    {grade.setText("C2");}

    else if(b<=34&&b>=0)
    {grade.setText("D");}

    else {grade.setText("");}

4 个答案:

答案 0 :(得分:5)

java.lang.NumberFormatException: For input string: " 34"

在使用解析方法之前修剪空格的String

try {

    int sub1_ = Integer.parseInt(sub1.getText().trim());
    int sub2_ = Integer.parseInt(sub2.getText().trim());
    int sub3_ = Integer.parseInt(sub3.getText().trim());
    int sub4_ = Integer.parseInt(sub4.getText().trim());
    int sub5_ = Integer.parseInt(sub5.getText().trim());

} catch (NumberFormatException e) {

    // invalid input

}

答案 1 :(得分:2)

在某些时候,您尝试解析整数“34”,前导空格是解析方法的问题。

你应该确保你的整数在创建它时没有空格,或者使用trim()函数来删除前导和尾随空格,

答案 2 :(得分:2)

除已报告的问题外,第int b = (a/500)*100;行应为int b = (a * 100) / 500;或更简单,int b = a/5;。除以500舍入为整数,因此如果a小于500,则结果为零。

答案 3 :(得分:0)

除了问题之外,还有一种方法可以减少代码中的混乱。

例如,您有多个if语句,它们都执行相同的操作,但编号不同。 在这种情况下,您只需创建一个函数。

private boolean inRangeOf(int value, int max, int min) {

    return value <= max && value >= min;

}

然后,您可以通过拨打inRangeOf(x, a, b)

来替换您的条件
if( inRangeOf(b, 100, 91) ) {

    grade.setText("A1");

}

else if( inRangeOf(b, 90, 81) ) {

    grade.setText("A2");

}

else if( inRangeOf(b, 80, 71) ) {

    grade.setText("B1");

}
相关问题