I’m playing around with a GUI Sudoku solver that uses an array of JTextFields (gridArray) for display and an int array (sudokuGrid) for the actual solving. When I run it and it tries to cast the JTextField strings to ints, it throws a NumberFormatException on parsing the strings into ints, specifically this message:
java.lang.NumberFormatException: For input string: ""
Here’s the section of code that’s causing me trouble:
// 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
I thought that the if–else would catch the empty fields and only try the parseInt if there was a value present, but if anyone can enlighten me I’d appreciate it.
Your problem is here:
You can’t compare strings that way. Do it this way instead: