0

所以我一直试图弄清楚这一点,但无济于事。我必须将 JTextField 转换为 int 数组,同时有两个异常 NumberFormatException 和 ArrayIndexOutOfBoundsException。我能够找到一种方法来转换它,但是当我输入字母时它不会抛出 NumberFormatException 。

try {
    int j=0;
    String str = "" + numbersField.getText();
    char digit[] = str.toCharArray();
        for (int i=0; i<digit.length; i++) {
            if (Character.isDigit(digit[i])) {
                array[j]=Character.getNumericValue(digit[i]);
                System.out.print(array[j] + " "); //Checking if it works
                ++j;
            }
        }
    } catch (NumberFormatException e1) {
        System.err.println("NumberFormatException: Array can only hold integers");

    } catch (ArrayIndexOutOfBoundsException e1) {
                System.err.println("ArrayIndexOutOfBoundsException: Array can only hold up to 10 elements");
    }

就个人而言,我相信它不会抛出 NumberFormatException,因为它将 JTextField 转换为 char,但我可能完全错了。任何帮助表示赞赏。

编辑:我只包含了程序的一部分,因为在我看来它有点长。数组在此之前被初始化。这部分程序的最终目标是让用户输入最多 10 个数字,同时在输入字母或超过 10 个数字时抛出异常。这是我第一次使用异常,所以我对它还是比较陌生,所以请原谅我犯的任何错误。

4

2 回答 2

2

您可以检查整个文本是否只有数字,然后将文本转换为int然后将所有数字放入数组。

尝试替代方案:

String str = numbersField.getText();

try {
    int value = Integer.parseInt(str);

    int[] array = new int[str.lenght - 1];
    j = array.length - 1;
    while (value > 0) {
        array[j] = value % 10;
        value /= 10;
        --j;
    }

} catch (NumberFormatException ex) {
    System.out.println("Enter only digits!")
}

UPD:您还需要检查是否value < 0并显示错误(如果您不接受减号)并在转换为 int 之前使用 str.trim()

于 2012-06-17T20:20:54.297 回答
1

嗯,也许这可能会有所帮助,也许不是最有效的,但可以完成它的工作:

    import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class JTextFieldIntToArrayValidation extends JFrame {

    private int[] integerArray;
    private JButton button;
    private JTextField tf;

    public JTextFieldIntToArrayValidation() {
        createAndShowUI();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JTextFieldIntToArrayValidation test = new JTextFieldIntToArrayValidation();
                test.setVisible(true);
            }
        });
    }

    private void createAndShowUI() {
        setTitle("Converting JTextField to an int array with exceptions");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        addComponentsToPane();
        addListeners();
        pack();
        tf.grabFocus();
    }

    private void addComponentsToPane() {
        button = new JButton("Convert JTextfield to array");
        tf = new JTextField(10);
        getContentPane().add(tf, BorderLayout.EAST);
        getContentPane().add(button, BorderLayout.WEST);
    }

    private void addListeners() {
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                String tmp = tf.getText();
                char[] chars = tmp.toCharArray();
                integerArray = new int[chars.length];

                try {

                    if (integerArray.length > 10) {//if digits entered are greater then 10. This however only allows for single digits!!!
                        throw new ArrayIndexOutOfBoundsException("Array cannot be larger then 10: " + integerArray.length);
                    }
                    for (int i = 0; i < tmp.length(); i++) {
                        if (!Character.isLetter(chars[i])) {//if its not a letter
                            integerArray[i] = Integer.parseInt(chars[i] + "");//stops java handling chars as ints
                        } else {//its a letter
                            throw new NumberFormatException("Only valid integers must be entered no letters: " + chars[i]);
                        }
                    }
                    printArray();
                } catch (NumberFormatException | ArrayIndexOutOfBoundsException ex) {
                    JOptionPane.showMessageDialog(getContentPane(), ex.getMessage());
                }
            }
        });
    }

    private void printArray() {
        for (int i : integerArray) {
            System.out.println(i);
        }
    }
}
于 2012-06-17T20:41:30.017 回答