我正在尝试在我的类中为我的 GUI 编写一些验证代码。我将如何将 JTextField 中的文本获取到 while 语句中并提示 JOptionPane 用户输入必要的数字( double )?更具体地说,如何检查从 JTextField 获取的内容是否是字符串/字符串+数字/数字以外的任何内容?
String text=JTextField.getText();
while(text.equals*a string or anything but a number*);
JOP("Invalid input ............ etc...
如果你有时间,这是我的 GUI 和我的类(class)。我正在尝试对其余方法执行此操作。但上面的答案就足够了。
http://www.mediafire.com/?f079i1xtihypg1b
http://www.mediafire.com/file/f079i1xtihypg1b/FinanceGUI.java
更新:
这是我到目前为止所拥有的:
//get the text entered in the amountRentText
//JTextField and parse it to a Double
String amtRentIn=amountRentText.getText();
try{Double.parseDouble(amtRentIn);}
catch(NumberFormatException nfe){
while()
amtRentIn=JOptionPane.showInputDialog("Invalid input. Please "+
"enter your rent: ");
}
double rent= Double.parseDouble(amtRentIn);
fin.setRent(rent);
这段时间我该放什么?
最佳答案
String amtRentIn=amountRentText.getText();
boolean incorrect = true;
while(incorrect){
try{Double.parseDouble(amtRentIn);incorrect = false;}
catch(NumberFormatException nfe){
amtRentIn=JOptionPane.showInputDialog("Invalid input. Please "+
"enter your rent: ");
}
}
关于java - 检查 JTextField 中的文本是否为某种数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4425357/