Java中的异常错误

时间:2013-02-06 03:43:00

标签: java exception awt

我创建了一个将十进制转换为二进制的java程序,反之亦然。我的十进制到二进制没有任何问题。但是当我将二进制编码为十进制时,我得到以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at converter.actionPerformed(converter.java:42)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6382)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
at java.awt.Component.processEvent(Component.java:6147)
at java.awt.Container.processEvent(Container.java:2083)
at java.awt.Component.dispatchEventImpl(Component.java:4744)
at java.awt.Container.dispatchEventImpl(Container.java:2141)
at java.awt.Component.dispatchEvent(Component.java:4572)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
at java.awt.Container.dispatchEventImpl(Container.java:2127)
at java.awt.Window.dispatchEventImpl(Window.java:2489)
at java.awt.Component.dispatchEvent(Component.java:4572)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:704)
at java.awt.EventQueue.access$400(EventQueue.java:82)
at java.awt.EventQueue$2.run(EventQueue.java:663)
at java.awt.EventQueue$2.run(EventQueue.java:661)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$3.run(EventQueue.java:677)
at java.awt.EventQueue$3.run(EventQueue.java:675)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:674)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

这是我的代码:

    import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class converter  extends JFrame implements ActionListener {

    JTextField txt1;
    JTextField txt2;
    JLabel lbl1;
    JLabel lbl2;
    JButton b1;
    JButton b2;

    public converter(){
        Container c = getContentPane();
        JPanel jp = new JPanel();
        c.add(jp);
        jp.add(lbl1=new JLabel("Decimal: "));
        jp.add(txt1=new JTextField(10));
        jp.add(lbl2=new JLabel("Binary: "));
        jp.add(txt2=new JTextField(10));
        jp.add(b1=new JButton("Convert"));
        jp.add(b2=new JButton("Clear"));
        b1.addActionListener(this);
        b2.addActionListener(this);

    }

    public static void main(String[] args) {
        converter cvt = new converter();
        cvt.setResizable(false);
        cvt.setVisible(true);
        cvt.setSize(250,150);
        cvt.setTitle("Decimal - Binary Converter");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

        String num = txt1.getText();
        int i = Integer.parseInt(num);
        if(txt1 != null && e.getSource() == b1){
            String z = Integer.toBinaryString(i);
            txt2.setText(z);
        }
        else if(e.getSource() == b2){
            txt1.setText("");
            txt2.setText("");
        }
        else if(txt2 != null && e.getSource() == b1){
            int x = Integer.parseInt(txt2.getText().trim(), 2);
            txt1.setText(""+x);
        }
    }

}
你可以指出出了什么问题吗?什么是它的解决方案。

4 个答案:

答案 0 :(得分:1)

您的代码中没有任何边界检查。 Aka,你有两个文本输入和一个'转换'功能,但该功能适用​​于以下所有组合:

  • 给出小数输入和二进制输入
  • 省略了十进制输入和二进制输入
  • 给出小数输入,省略二进制输入
  • 省略小数输入,给出二进制输入

您需要决定在所有四种情况下做什么,然后适当地进行解析。这些案例中有四分之三非常容易处理 - 当用户填写十进制和二进制输入字段然后命中转换时,您必须做出决定该做什么(我建议显示错误对话框)那个案子)。

就目前而言,您正在解析所有情况下的十进制输入字段,当其左侧空白时,将转换为:

Integer.parseInt("")

按预期抛出NumberFormatException


我会处理你可能遇到的四种情况:

public static boolean isEmpty(final String str) {
    return (str == null || str.trim().equals(""));
}

final String decimalInput = text1.getText();
final String binaryInput = text2.getText();

if(! isEmpty(decimalInput)) {
    if( ! isEmpty(binaryInput)) {
        // Decimal input and Binary input are both given, show error
    } else {
        // Decimal input is given, Binary input is omitted, convert to binary
    }
} else {
    if( isEmpty(binaryInput)) {
        // Decimal input and Binary input are both omitted, show error
    } else {
        // Decimal input is omitted, Binary input is given, convert to decimal
    }
}

答案 1 :(得分:0)

检查txt1txt2值是否为数字。

答案 2 :(得分:0)

跟踪的第一行显示当程序尝试将空字符串("")转换为int时,会引发错误。如果您进一步查看跟踪(第5行),则会在actionPerformed方法中发生错误。特别是,行:

String num = txt1.getText();
int i = Integer.parseInt(num);

您可以通过首先检查字符串是否为空来解决此问题:

if (num.length() < 1)
  // tell user they must enter a number

答案 3 :(得分:0)

有些事情会浮现在脑海中。

您可以捕获异常并显示一条消息,告诉用户他们输入的值无效。您还应该trim来自该字段的结果,以确定。

public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

    try {      
        String num = txt1.getText().trim(); // <-- Trim the incoming value
        int i = Integer.parseInt(num);
        if(txt1 != null && e.getSource() == b1){
            String z = Integer.toBinaryString(i);
            txt2.setText(z);
        }
        else if(e.getSource() == b2){
            txt1.setText("");
            txt2.setText("");
        }
        // I'm not sure if this a logic error or not, but txt2 is text field...
        // Did you think it was the text from the field??
        else if(txt2 != null && e.getSource() == b1){
            int x = Integer.parseInt(txt2.getText().trim(), 2);
            txt1.setText(""+x);
        }
    } catch (NumberFormatException exp) {
        // Display message...
    }
}

另一种方法是使用DocumentFilter来阻止用户输入对字段无效的任何值。

结帐Text Component Featuresexamples

<强>更新

你也有一些逻辑错误......

txt1txt2永远不可能是null,除非你做了一些可怕的错误......

你应该检查一下按下了什么按钮,这样你就可以更清楚地决定如何进步。

然后,您应该检查字段中的文本并确定要继续的转换路径...

try {
    if (e.getSource() == b1) {
        String dec = txt1.getText();
        String bin = txt2.getText();

        if (dec != null && dec.trim().length() > 0 &&
            bin != null && bin.trim().length() > 0) {
            // Both fields are filled out?!
        } else if (dec != null && dec.trim().length() > 0) {
            String value = txt1.getText();
            int i = Integer.parseInt(dec);
            String z = Integer.toBinaryString(i);
            txt2.setText(z);
        } else if (bin != null && bin.trim().length() > 0) {
            int x = Integer.parseInt(bin, 2);
            txt1.setText("" + x);
        }
    } else if (e.getSource() == b2) {
        txt1.setText("");
        txt2.setText("");
    }
} catch (NumberFormatException exp) {
    exp.printStackTrace();
}