我在寫一個類來驗證來自另一個類的輸入。似乎一切似乎工作,但我的驗證將不會接受確切的高範圍價值。我不知道爲什麼它不接受它 - 例如,如果highRange是10,用戶輸入10,!(10> 10)。如果你們可以關心我的代碼,我將不勝感激!字符串到整數輸入驗證轉換
import javax.swing.JOptionPane;
public class InputVerification {
private String input;
private int lowRange;
private int highRange;
private int invalidNum;
public InputVerification(String input, int lowRange, int highRange, int invalidNum) {
this.input = input;
this.lowRange = lowRange;
this.highRange = highRange;
this.invalidNum = invalidNum;
}
public int intVerify() {
String userInput = null;
int intInput = 0;
do {
do {
try {
/**
* handles any text entered instead of numbers enter -2 if
* you don't need an invalid number
*/
userInput = JOptionPane.showInputDialog(this.input);
intInput = Integer.parseInt(userInput);
if ((intInput > highRange || intInput < lowRange) && !(userInput.matches("[a-zA-Z]+"))) {
JOptionPane.showMessageDialog(null,
"Error! Please pick a number between " + lowRange + "-" + highRange + ".");
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,
"Error! Please pick a number between " + lowRange + "-" + highRange + ".");
}
} while (!userInput.matches("^[0-9]"));
if ((intInput > highRange || intInput < lowRange)) {
/**
*
* sends an error message if the number is higher than 100 or
* lower than 1 as long as the input was not text
*
*/
JOptionPane.showMessageDialog(null,
"Error! Please pick a number between " + lowRange + "-" + highRange + ".");
}
if (invalidNum != -2 && intInput == invalidNum) {
JOptionPane.showMessageDialog(null, "Error! Please pick a number between " + lowRange + "-" + highRange
+ " that is not " + invalidNum + ".");
}
} while ((intInput > highRange || intInput < lowRange || intInput == invalidNum)
&& !(userInput.matches("[a-zA-Z]+")));
return intInput;
}
}
您應該定義一個布爾函數來驗證整數並從GUI中使用它。 – Aubin
歡迎來到堆棧溢出!它看起來像你需要學習使用調試器。請幫助一些[互補調試技術](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。如果您之後仍然有問題,請隨時返回更多詳情。 –
@JoeC謝謝,我會檢查出來! –