【问题标题】:How to check for user input error when initializing a class in java在java中初始化类时如何检查用户输入错误
【发布时间】:2014-11-16 19:23:21
【问题描述】:

如何在 java 中初始化类时检查输入错误? 我已经包含了一个示例

public class Date {
private int d;
private int m;
private int y;    

public Date(int d, int m, int y) {
    if(is valid date){
      this.d = d;
      this.m = m;
      this.y = y; //etc
    } else {
      //  ??????
      // throw an exception?
    }   
  }
}

【问题讨论】:

  • 如果您需要数据验证,我建议您使用 Builder 模式或工厂方法

标签: java error-handling user-input


【解决方案1】:

我想你可以走几种方式:
- 你可以简单地抛出一个异常 - 考虑一下你是要使用 Checked 还是 Unchecked Exceptions

-您可以执行denispyr 建议的操作。

public class Date {
    private int d;
    private int m;
    private int y;    

public static Date createNewDate(int d, int m, int y) throws IllegalArgumentException {
     // your checks here

     return new Date(int d, int m, int y);
}

private Date(int d, int m, int y) {
    this.d = d;
    this.m = m;
    this.y = y; //etc
  }
}

您可以在创建方法中声明异常。

查看以下链接: - Is it good practice to make the constructor throw an exception? - Can constructors throw exceptions in Java?

所以如果没有第二个环节的点(构造函数中的资源分配,终结器攻击),我想在构造函数中抛出没有什么问题。

【讨论】:

    【解决方案2】:

    我会这样做:

    import java.io.IOException;
    public class Date() {
        private int d, m, y;
        public Date(int d, m, y) throws IOException {
            final int currentYear=2014;
            if (d<0||m<0||y<0||d>31||m>12||y>currentYear) throw new IOException();
            //will exit if there is illegal input
            this.d=d;
            //et cetera
    }
    }
    

    注意:强烈建议您实际抛出错误,而不是尝试处理错误输入,因为很有可能,给您错误输入的程序员会想知道它是什么并尝试修复它,因为该程序可能正在做一些他认为不同的事情。

    【讨论】:

    • 如果月份是四月,一天是 31 怎么办?那应该是非法约会!
    【解决方案3】:
    static ArrayList<Integer> monthsWithThirtyDays=new ArrayList<Integer>(Arrays.asList(new Integer[]{1,3,5,7,8,10,12}));
    
    private int d, m, y;
    
    public static boolean isValidDate(int d, int m, int y) {
        if(y<=0) // Year can't be below or equal to 0
            return false;
    
        if(!(m>0 && m<=12)) // Month can't be under 0 or above 12
            return false;
    
        if(monthsWithThirtyDays.contains(m)) { // If the month has 30 days
            if(!(d>0 && d<=30))// Day can't be below 0 or above 30
                return false;
        } else if(m==2){ // If the month is February
            if(y%4==0) { // If it has 29 days
                if(!(d>0 && d<=29)) //Day can't be below 0 or above 29
                    return false;
            } else { // If it has 28 days
                if(!(d>0 && d<=28)) // Day can't be below 0 or above 28
                    return false;               
            }
        } else { // If the month has 31 days
            if(!(d>0 && d<=31)) // Day can't be below 0 or above 31
                return false;
        }
    
        return true;
    }
    
    public Date(int d, int m, int y) throws Exception {
    if(isValidDate(d,m,y)) {
        this.d=d; this.m=m; this.y=y;
    } else {
        throw new Exception();
    }
    

    }

    这也适用于每 4 年的 2 月 29 日。

    让我知道它是否有效(或无效)
    快乐的编码:) -查理

    【讨论】:

      【解决方案4】:

      您可以使用 SimpleDateFormat 类的 parse 方法来检查日期是否有效。如果日期无效,parse 方法将抛出 ParseException。

      public class Date {
      private int d;
      private int m;
      private int y;    
      
      public Date(int d, int m, int y) throws ParseException {
            String dateToValidate = y+"-"+m+"-"+d;
      
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.setLenient(false);
            Date date = sdf.parse(dateToValidate);
      
            this.d = d;
            this.m = m;
            this.y = y;
      
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-12
        • 1970-01-01
        • 2013-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-02
        • 1970-01-01
        相关资源
        最近更新 更多