日期验证在Java中失败

huangapple go评论145阅读模式
英文:

Date Validation in Java fails

问题

我完全是个新手对于Java编程,我正在尝试创建一个Java FX项目。我已经按照关于日期验证方法的教程进行了操作,但似乎出现了问题。在这个特定的部分,我必须创建一个由用户在文本字段中插入的对象列表。其中包括一个日期,但它需要是有效的。

在下面的这段代码中,我需要进行验证的对象是 datep。我创建了一个方法,在这个方法中,如果字符串是有效的,它应该将我的标志设置为true并返回它。在创建列表之前,我插入了一个 if 语句,以检查我的 flag 是否设置为true,这意味着日期根据格式得到了验证。当我运行它时,它会创建列表,即使日期无效也是如此。我是不是把if语句放错了地方?因为我认为方法是正确的。

@Override
public void handle(MouseEvent event) {
    if (event.getSource() == NewrentBtn) {
    
    String vehiclen = OximaTxT.getText();
    String clientn = ClientTxT.getText();
    String store = StoreTxT.getText();
    String storer = StorerTxT.getText();
    String timerp = TimeTxT.getText();
    String timer = TimerTxT.getText();
    String datep = DateTxT.getText(); // <-------------
    String dater = DaterTxT.getText();
    Integer sum = Integer.parseInt(SumTxT.getText());	 
    if(flag = true) { // <------------
        createRental(id, vehiclen, store, datep, timerp, clientn, storer, dater, timer, sum);
        clearTextFields();
    }
}

public boolean Checkdate(String datep) { // <-------------
    
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Date BOD = null;
    df.setLenient(false);
    
    try
    {
        BOD = df.parse(datep); // <----------------
        flag = true;
    }
    catch(Exception e)
    {
        flag = false;
    }
    return flag;
}

public void createRental(int id,String vehiclen,String store,String datep,String timerp,String clientn,String storer,String dater,String timer,int sum ) {
    Rental m = new Rental(id,vehiclen,store,datep,timerp,clientn,storer,dater,timer,sum);
    RentalList.add(m);
    rentalTableView.getItems().add(m);
            
}
英文:

I'm totally new to Java programming and I'm trying to create a Java FX project. I've followed tutorials about the date validation method but it seems to fail.In this certain part I have to make a list with objects inserted by a user in text fields. That includes a date but it needs to be valid.

Below in this piece of code, the object I need to get validated is datep . I've created a method in which if the string is valid, it should set my flag to true and return it. Before the list is created I inserted an if statement to check whether that my flag is set to true which means that the date is verified according to the format.When I run it,it creates the list whatsoever even if the date is invalid.Am I putting the if statement in the wrong part? Cause I think the method is fine.

@Override
public void handle(MouseEvent event) {
    if (event.getSource() == NewrentBtn) {
    
    String vehiclen =OximaTxT.getText();
    String clientn = ClientTxT.getText();
    String store = StoreTxT.getText();
    String storer = StorerTxT.getText();
    String timerp = TimeTxT.getText();
    String timer = TimerTxT.getText();
    String datep = DateTxT.getText(); // <-------------
    String dater = DaterTxT.getText();
    Integer sum = Integer.parseInt(SumTxT.getText());	 
    if(flag = true) { // <------------
        createRental(id, vehiclen, store, datep, timerp, clientn, storer, dater, timer, sum);
        clearTextFields();
    }
}

public boolean Checkdate(String datep) { // <-------------
    
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Date BOD = null;
    df.setLenient(false);
    
    try
    {
        BOD = df.parse(datep); // <----------------
        flag = true;
    }
    catch(Exception e)
    {
        flag = false;
    }
    return flag;
}

public void createRental(int id,String vehiclen,String store,String datep,String timerp,String clientn,String storer,String dater,String timer,int sum ) {
    Rental m = new Rental(id,vehiclen,store,datep,timerp,clientn,storer,dater,timer,sum);
    RentalList.add(m);
    rentalTableView.getItems().add(m);
            
}

答案1

得分: 1

根据您试图实现的目标,这是我对修改代码的建议。

首先,让我向您解释我发现的两个问题:第一个问题是您在接收文本输入并存储标志变量时,缺少对日期的验证方法的调用,即对CheckDate(datep)的调用,或者看起来是这样,因为我们没有完整的代码(这是可以的);第二个问题是在if(flag = true)中缺少了一个=,应该是if(flag == true)

所以下面是完整的代码:

@Override
public void handle(MouseEvent event) {
    if (event.getSource() == NewrentBtn) {

        String vehiclen = OximaTxT.getText();
        String clientn = ClientTxT.getText();
        String store = StoreTxT.getText();
        String storer = StorerTxT.getText();
        String timerp = TimeTxT.getText();
        String timer = TimerTxT.getText();
        String dater = DaterTxT.getText();
        Integer sum = Integer.parseInt(SumTxT.getText());
        String datep = DateTxT.getText();

        boolean flag = Checkdate(datep);
        if (flag == true) {
            createRental(id, vehiclen, store, datep, timerp, clientn, storer, dater, timer, sum);
            clearTextFields();
        }
    }
}

通过这种方式,您可以验证日期是否按照您的方案正确格式化,并在满足条件时继续处理过程。

最后,鉴于您刚开始学习Java编程,我有三点建议:

  1. 所有方法的第一个字母应始终为小写,例如public boolean checkDate()。这样您可以区分方法和类,类始终以大写字母开头,例如public class Product。唯一的例外是类的构造函数。
  2. 您不应该将“图形界面”逻辑与“逻辑处理”逻辑混合在一起。也就是说,您应该将处理部分放在一个包中,将图形组件放在另一个包中,并通过在“图形界面”中创建“处理逻辑”的实例来关联两者。
  3. 用户输入验证应该直接在处理程序方法中使用try-catch子句进行,如下所示。
public void handle(MouseEvent event) {
    if (event.getSource() == NewrentBtn) {

        String vehiclen = OximaTxT.getText();
        String clientn = ClientTxT.getText();
        String store = StoreTxT.getText();
        String storer = StorerTxT.getText();
        String timerp = TimeTxT.getText();
        String timer = TimerTxT.getText();
        String dater = DaterTxT.getText();
        Integer sum = Integer.parseInt(SumTxT.getText());
        try {
            String datep = DateTxT.getText();
            SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            df.parse(datep);
            createRental(id, vehiclen, store, datep, timerp, clientn, storer, dater, timer, sum);
            clearTextFields();
        } catch (ParseException e) {
            /* 在这里处理失败时发生的情况,您可以创建一个JDialog来显示错误,
            或者创建警报,根据您的需求进行处理 */
            e.printStackTrace();
        }
    }
}

这样就得到了一个更清晰的版本。

英文:

From the looks of what you are trying to achieve here is my suggestion to modify the code.

First of all let me explain to you two issues i found: the first one is that you are missing the call to the validation method of the Date, that is the call to the CheckDate(datep) when you receive the text input and store the flag variable, or so it seems as we dont have the full code (which is ok ); and second you are missing a =in the if(flag = true), it should be if(flag == true)

So here is the full code:

@Override
public void handle(MouseEvent event) {
if (event.getSource() == NewrentBtn) {
String vehiclen =OximaTxT.getText();
String clientn = ClientTxT.getText();
String store = StoreTxT.getText();
String storer = StorerTxT.getText();
String timerp = TimeTxT.getText();
String timer = TimerTxT.getText();
String dater = DaterTxT.getText();
Integer sum = Integer.parseInt(SumTxT.getText());
String datep = DateTxT.getText();
boolean flag = Checkdate(datep);
if(flag == true) {
createRental(id,vehiclen,store,datep,timerp,clientn,storer,dater,timer,sum);
clearTextFields();
}
}
}

This way you are verifying if the date is correctly formatted and continue the process if it is according to your scheme.

Finally i have three recommendations as you are new to java programming:

  1. For all methods the first letter should always be in lowercase like public boolean checkDate() this way you can differentiate a method from a Class, which will always start in Uppercase like public class Product. The only exception for this is the constructor of a class.
  2. You should never mix the graphical interface logic, with the logical processing logic. This is: you should keep the processing part in one package and the graphic component in another and relate both of them by creating an instance of the processing logic in the graphical interface.
  3. The user input validation should be directly made in the handler method with try-catch clauses like the following.

Here:

public void handle(MouseEvent event) {
if (event.getSource() == NewrentBtn) {
String vehiclen =OximaTxT.getText();
String clientn = ClientTxT.getText();
String store = StoreTxT.getText();
String storer = StorerTxT.getText();
String timerp = TimeTxT.getText();
String timer = TimerTxT.getText();
String dater = DaterTxT.getText();
Integer sum = Integer.parseInt(SumTxT.getText());
try {
String datep = DateTxT.getText();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.parse(date);
createRental(id,vehiclen,store,datep,timerp,clientn,storer,dater,timer,sum);
clearTextFields();
} catch (ParseException e) {
/* Here you handle what happens when if fails, you can create a JDialog to show
the error or create an alert, whatever you need */
e.printStackTrace();
}
}
}

And voila a cleaner version

huangapple
  • 本文由 发表于 2020年8月21日 09:29:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63515261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定