我的代碼過早地拋出了預期的錯誤。我試圖測驗輸入驗證,但在驗證發生之前我拋出了一個錯誤。當我嘗試將我的代碼恢復到以前運行良好的版本時,它會拋出我現在正在處理的相同錯誤,然后才出現問題。
輸入示例
下面的代碼是第 137 行- 明顯的罪犯
int playerGuess = Integer.parseInt(playerGuessField.getText().trim());
private void guessButtonClicked(){
Validators validGuess = new Validators(this);
int guessesRemaining = Integer.parseInt(guessesRemainingField.getText());
int playerGuess = Integer.parseInt(playerGuessField.getText().trim());//error is thrown here
if(validGuess.isValidGuess(playerGuessField, "guess")){
//more code here but not necessarily relevant
}
}
//basic structure of my validators
public boolean isValidGuess(JTextComponent c, String fieldName){
try {
int validGuess = Integer.parseInt(c.getText());
if(validGuess >= 1 && validGuess <= 10){
return true;
} else {
showErrorDialog("Your " fieldName " must be between 1 & 10");
c.requestFocusInWindow();
return false;
}
} catch (NumberFormatException e) {
showErrorDialog("Your " fieldName " must be between 1 & 10");
c.requestFocusInWindow();
return false;
}
}
這是所有榮耀中的例外。
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "asdf"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:660)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at GameGUI.guessButtonClicked(GameGUI.java:137)
at GameGUI.lambda$0(GameGUI.java:94)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6617)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
at java.desktop/java.awt.Component.processEvent(Component.java:6382)
at java.desktop/java.awt.Container.processEvent(Container.java:2264)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4993)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2322)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4934)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4563)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4504)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2308)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2773)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
uj5u.com熱心網友回復:
底線:您需要驗證您的輸入。
為此,我可以想到幾個選項:
選項 1:Scanner用于檢查輸入是否為數字
Scanner scanner = new Scanner(playerGuessField.getText().trim());
if (scanner.hasNextInt()) {
int playerGuess = scanner.nextInt();
} else {
// handle the error
}
選項 2:將第 137 行換成try/catch
int playerGuess = 0;
try {
playerGuess = Integer.parseInt(playerGuessField.getText().trim());
} catch (NumberFormatException nfe) {
// handle the exception
}
選項 3:將輸入驗證器添加到文本欄位。
為此,您需要創建一個輸入驗證器
public class MyInputVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
try {
BigDecimal value = new BigDecimal(text);
return true; // or some other evaluation (i.e. value > 0 for positive value)
} catch (NumberFormatException e) {
return false;
}
}
}
然后,您需要將其添加到該欄位
field.setInputVerifier(new MyInputVerifier());
最后,您需要觸發驗證。這通常在呈現表單時完成。我的示例是使用ActionListener.
btn.addActionListener(e -> {
if (!field.getInputVerifier().verify(field)) {
System.out.println("Not valid. Clear!");
field.setText("");
}
});
選項 4:使用DocumentListener
public class InputVerifierDemo {
private static JLabel errorMsg = new JLabel("Invalid input");
private static JFrame frame = new JFrame();
public static void main(String[] args) {
JTextField field = new JTextField(10);
// field.setInputVerifier(new MyInputVerifier());
JButton btn = new JButton("Click Me!");
// btn.addActionListener(e -> {
// if (!field.getInputVerifier().verify(field)) {
// System.out.println("Not valid. Clear!");
// field.setText("");
// }
// });
JPanel panel = new JPanel();
errorMsg.setForeground(Color.RED);
errorMsg.setVisible(false);
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 0, 0, 5);
c.gridx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.SOUTH;
panel.add(errorMsg, c);
c.gridx = 1;
c.gridy = 1;
c.anchor = GridBagConstraints.CENTER;
panel.add(field, c);
field.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
validateInput(field);
}
@Override
public void insertUpdate(DocumentEvent e) {
validateInput(field);
}
@Override
public void changedUpdate(DocumentEvent e) {
} // Not needed for plain-text fields
});
frame.getContentPane().add(panel);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static void validateInput(JTextField field) {
String text = field.getText();
String pattern = "\\d ";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(text);
if (m.matches()) {
errorMsg.setVisible(false);
} else {
errorMsg.setVisible(true);
}
}
private static class MyInputVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
try {
BigDecimal value = new BigDecimal(text);
return true; // or some other evaluation (i.e. value > 0 for positive value)
} catch (NumberFormatException e) {
return false;
}
}
}
}
The code above contain the input verifier AND the document listener solutions so that you could play with both. I personally prefer the document listener because it is more interactive. I rather validate fields as I am typing on them, rather than after the fact when all the fields are filled and an action to submit the form takes place. But, this is all a matter of personal preference.
I credit MadProgrammer for option #1.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434496.html
上一篇:使用掃描儀讀取檔案時如何處理空格
