簡體   English   中英

為什么此Java代碼會引發NumberFormatException?

[英]Why does this Java code throw a NumberFormatException?

我正在玩一個GUI Sudoku解算器,該解算器使用JTextFields數組( gridArray )進行顯示,並使用int數組( sudokuGrid )進行實際求解。 當我運行它,它試圖投的JTextField string s到int S,它拋出一個NumberFormatException的解析string s轉換int S,特別是這條消息:

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

這是引起我麻煩的代碼部分:

// create solveButton
    solveButton = new JButton("Solve It!");
    solveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                // create grid and call Solve()
                for(int i=0;i<9;i++) {
                    for(int j=0;j<9;j++) {
                        if (gridArray[i][j].getText() == "")
                            {sudokuGrid[i][j] = 0;}
                        else {sudokuGrid[i][j] = Integer.parseInt(gridArray[i][j].getText());}
                    }
                } // end for loop

                Solver(sudokuGrid);

                // display solution
                for(int i=0;i<9;i++) {
                    for(int j=0;j<9;j++) {
                        gridArray[i][j].setText(String.valueOf(sudokuGrid[i][j]));
                    }
                } // end for loop
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(mainFrame,e.toString(),"Number Format Exception",JOptionPane.ERROR_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(mainFrame,"Sorry, something broke, try again.","Solve Error",JOptionPane.ERROR_MESSAGE);
            } // end try-catch
        } // end actionPerformed()
    }); // end solveButton ActionListener

我認為if - else將捕獲空字段,並且僅在存在值的情況下才嘗試parseInt ,但是如果有人可以啟發我,我將不勝感激。

您正在使用==檢查字符串是否相等,這僅用於引用相等。 也許您打算寫:

gridArray[i][j].getText().equals("")

您的問題在這里:

  if (gridArray[i][j].getText() == "")

您不能那樣比較字符串。 改為這樣:

if (gridArray[i][j].getText().equals("")) 

不要要求TextArea作為文本,因為它可能仍處於編輯過程中。 檢查基礎文檔本身。

Document document = gridArray[i][j].getDocument();
sudokuGrid[i][j] = document.getLength() == 0 ? 0 : Integer.parseInt(document.getText(0, 1);

另外...為什么要使用JTextArea? 為什么不使用JTextField? 您甚至可以將其與JSpinner結合使用,該JSpinner的值從0(被解釋為到9)。

對字符串使用== -comparison並不意味着檢查文本(字符串內容)是否相等,而是檢查字符串對象的相等性(測試它們是否具有完全相同的對象)。 使用String.equals()代替。

問題是您的平等性檢查:

gridArray[i][j].getText() == ""

這不能滿足您的預期。 在Java中,它檢查兩個字符串是否是同一對象,而不是它們的值是否相等。 您應該使用String.equals()方法來評估文本字段是否為空。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM