简体   繁体   English

Java的。 限制日期的值

[英]Java. Restricting the values for a Date

It might seem like a stupid question to you guys, but I'm a java noob and still trying to grasp the whole concept. 对你们来说,这似乎是一个愚蠢的问题,但是我是一个Java新手,并且仍在尝试掌握整个概念。 So, I basically have a simple theatre management system that allows me to add groups to the database. 因此,我基本上有一个简单的剧院管理系统,可以将组添加到数据库中。 To each group, you can add students that each have a unique student ID and a name. 您可以向每个组添加每个学生都有唯一的学生ID和名称的学生。 You can also add rehearsal dates to a group. 您还可以将排练日期添加到组中。 Both of these are stored in separate linked lists. 这两个都存储在单独的链接列表中。 This is my rehearsal object: 这是我的排练对象:

public Rehearsal(int d, int m, int y) {
    day = d;
    month = m;
    year = y;
}

This is the addRehearsal method in the group class: 这是组类中的addRehearsal方法:

public void addRehearsal(int d, int m, int y) {
    Rehearsal newrehearsal = new Rehearsal(d, m, y);
    if (!RehearsalDates.contains(newrehearsal)) {
        RehearsalDates.add(newrehearsal);
    }
    else
        JOptionPane.showMessageDialog(null, "Rehearsal already exists for this group!", "Error", JOptionPane.WARNING_MESSAGE);
}

My question is, how and where can I restrict what values can be entered. 我的问题是,如何以及在何处限制可以输入的值。 That means, that the program gives an error in the form of a message dialog if the value entered for int d > 31 or int m > 12. This is not really necessary for the year, as the user is allowed to create rehearsal dates for the past as well as the future. 这意味着,如果为int d> 31或int m> 12输入的值,则该程序将以消息对话框的形式给出错误消息。由于用户可以为用户创建排练日期,因此这一年实际上并不需要。过去和未来。

Thanks for your help guys :) 谢谢您的帮助:)

Validating dates is more complex than checking each parameter. 验证日期比检查每个参数更为复杂。 For example, calling it with (29, 2, 2000) would be invalid (recall that 2000 was not a leap year), even though all parameters are "within range". 例如,即使所有参数都在“范围内”,用(29, 2, 2000)调用它也是无效的(记得2000年不是 a年)。

The only sane way to check is to attempt to parse a Date from the parameters and catch the exception. 唯一明智的检查方法是尝试从参数解析Date并捕获异常。 There are a couple of ways to do this, but the simplest is this: 有两种方法可以执行此操作,但最简单的方法是:

public Rehearsal(int d, int m, int y) {
    try {
        sdf = new SimpleDateFormat("d-M-yyyy");
        sdf.setLenient(false);
        sdf.parse(d + "-" + m + "-" + y);
    } catch (ParseException e) {
        // the parameters are not valid
    }
    // rest of code
}

Note the call to setLenient() , which is required, otherwise invalid input "rolls over" to the next available valid date - for example 36-12-2012 would be parsed as 05-01-2013 . 请注意必须调用setLenient() ,否则无效的输入将“滚动”到下一个可用的有效日期-例如, 36-12-2012将被解析为05-01-2013

The best place to put this code would be in the constructor, throwing an exception: 放置此代码的最佳位置是在构造函数中,引发异常:

public Rehearsal(int d, int m, int y) {
    try {
        sdf = new SimpleDateFormat("d-M-yyyy");
        sdf.setLenient(false);
        sdf.parse(d + "-" + m + "-" + y);
    } catch (ParseException e) {
        // the parameters are not valid
        throw new IllegalArgumentException();
    }
    day = d;
    month = m;
    year = y;
}

And you would catch this wherever it is called. 无论在何处调用它,您都可以抓住它。

Rehearsal newrehearsal;
try {
    newrehearsal = new Rehearsal(1, 2, 3);            
} catch (IllegalArgumentException ex) {
    JOptionPane.showMessageDialog(null, "Invalid date input!", "Error", JOptionPane.WARNING_MESSAGE);
    return;
}
// rest of method

An even better design would be to pass a Date object, putting the onus on the caller to validate input, and there would be less throw and catch code. 更好的设计是传递Date对象,使调用者有责任验证输入,并且抛出和捕获的代码更少。

Why not throw an IllegalArgumentException from the constructor of Rehearsal and then catch it in the addRehearsal method: 为什么不从Rehearsal的构造函数中抛出IllegalArgumentException ,然后在addRehearsal方法中捕获它:

public Rehearsal(int d, int m, int y) {
    if (d < 1 || d > 31) {
        throw new IllegalArgumentException("Invalid day");
    }
    if (m < 1 || m > 12) {
        throw new IllegalArgumentException("Invalid month");
    }
    day = d;
    month = m;
    year = y;
}

And in the addRehearsal method catch the exception on construction: 并在addRehearsal方法中捕获构造异常:

Rehearsal newrehearsal;
try {
    newrehearsal = new Rehearsal(1, 2, 3);            
} catch (IllegalArgumentException ex) {
    JOptionPane.showMessageDialog(null, "Invalid date input!", "Error", JOptionPane.WARNING_MESSAGE);
    return;
}

That should be an intermediate solution - it will certainly prevent the creation of invalid dates. 那应该是一个中间解决方案-它肯定会防止创建无效日期。

You may then want to later add listeners on your inputs to prevent the invalid data in the first place. 然后,您可能希望稍后在输入中添加侦听器,以首先防止出现无效数据。

Finally, you may want to consider using a Calendar rather than a custom date object. 最后,您可能要考虑使用Calendar而不是自定义日期对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM