-2

我创建了一个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

4 回答 4

1

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

  • 十进制输入和二进制输入都给出
  • 十进制输入和二进制输入都省略
  • 给出十进制输入,省略二进制输入
  • 省略十进制输入,给出二进制输入

您需要决定在所有四种情况下要做什么,然后适当地进行解析。其中四分之三的情况非常容易处理 - 当用户同时填写十进制和二进制输入字段然后点击转换时,您必须决定要做什么(我建议在这种情况)。

就目前而言,您在所有情况下都在解析 Decimal 输入字段,当其留空时,这将转换为:

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
    }
}
于 2013-02-06T03:52:06.210 回答
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...
    }
}

另一种是使用 aDocumentFilter来防止用户输入任何对字段无效的值。

查看文本组件功能示例

更新

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

txt1并且txt2永远不可能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();
}
于 2013-02-06T03:54:28.570 回答
0

检查txt1txt2评估它是否是数字。

于 2013-02-06T03:46:14.887 回答
0

跟踪的第一行显示当您的程序尝试将空字符串 ( "") 转换为int. 如果进一步往下看(第 5 行),actionPerformed方法中会出现错误。特别是,这些行:

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

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

if (num.length() < 1)
  // tell user they must enter a number
于 2013-02-06T03:48:51.707 回答