有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查JTextField中的文本是否为特定的数据类型

我试图在我的类中为我的GUI编写一些验证代码。如何将JTextField中的文本输入while语句,并提示用户输入必要的数字(双精度)?更具体地说,如何检查我从JTextField中得到的是字符串/字符串+数字/除数字以外的任何内容

String text=JTextField.getText();

while(text.equals*a string or anything but a number*);
   JOP("Invalid input ............ etc...

如果你有时间,这是我的GUI和我的课程。我试图在剩下的方法中做到这一点。但上述问题的答案就足够了

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);

我在这段时间里放了什么


共 (3) 个答案

  1. # 1 楼答案

    我想到的一个“便宜”但不太漂亮的解决方案是使用Double。解析双(…)在该字符串上,并准备捕捉在该字符串包含任何非数字内容时发生的解析异常

  2. # 2 楼答案

    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: ");
     }
    
    }
    
  3. # 3 楼答案

    ^{}就是为此而设计的。你的verify()实现可以调用parseDuble()。这是另一个example