简体   繁体   English

Java main方法中的循环和异常处理

[英]Looping and exception handling in java main method

I working on a fairly basic problem: I am writing a java program that takes in strings for a day, month, and year (in integer form eg 24/9/2015) and then coverts this into a word based version of the date (eg 24th of September, 2015). 我正在研究一个相当基本的问题:我正在编写一个Java程序,该程序接受一天,月份和年份的字符串(以整数形式,例如24/9/2015),然后将其转换为日期的基于单词的版本(例如2015年9月24日)。

I also need to be able to handle a user from typing in "invalid" values for the above by creating my own exception classes. 我还需要能够通过创建我自己的异常类来处理用户从上面键入“无效”值的问题。

When an exception is thrown (for example the user inputs an "invalid" month), the program should prompt the user to re-enter only the incorrect value (so in this case it prompts them to re-enter just the month). 当引发异常时(例如,用户输入“无效”月份),程序应提示用户重新输入错误的值(因此,在这种情况下,它将提示用户重新输入月份)。

Here is the code I have written so far (you may assume the exception classes have been properly defined and work as they should): 这是我到目前为止编写的代码(您可以假设异常类已经正确定义并且可以正常工作):

import java.util.Scanner;

public class ParseDate {

public static void main(String args[]){

    String month, day, year;
    Scanner input = new Scanner(System.in);

    System.out.println("Enter the day: ");
    day = input.nextLine();
    System.out.println("Enter the month: ");
    month = input.nextLine();
    System.out.println("Enter the year: ");
    year = input.nextLine();

    try{
        formatDate(month, day, year);
    }
    catch(MonthException m){
        //?
    }
    catch(DayException d){
        //??
    }
    catch(YearException y){
        //???
    }
}

public static String formatDate(String month, String day, String year)
throws MonthException, DayException, YearException{
    String output;
    if (Integer.parseInt(month) < 1 || Integer.parseInt(month) > 12){
        throw new MonthException("Invalid month. reenter.");
    }
    if (Integer.parseInt(year) < 1000 || Integer.parseInt(year) > 3000){
        throw new MonthException("Invalid year. reenter.");
    }
    if (Integer.parseInt(day) < 1){
        throw new MonthException("Invalid day. reenter.");
        //extra code to handle the cases where the day is 
        //too large for the particular month and year entered
    }

    //other code here for converting date

    return output;
}
}

As you can probably see from my code, I am having trouble deciding where and how I should get the program to loop through the exceptions separately. 正如您可能从我的代码中看到的那样,我在确定应该在哪里以及如何使程序分别循环遍历异常时遇到麻烦。 I was thinking of possibly using a switch but I'm not too sure where to put it. 我本来想使用switch但不太确定该在哪里放置switch

How can I do this? 我怎样才能做到这一点?

So, basically, you need someway to maintain the information between loops, each time an exception is triggered, you need to invalidate only the information related to the exception. 因此,基本上,您需要某种方式来维护循环之间的信息,每次触发异常时,您只需要使与异常相关的信息无效即可。

You then need to continue looping until all the values are validated and the values can be formatted, for example... 然后,您需要继续循环直到所有值都经过验证并且可以格式化值为止,例如...

import java.util.Scanner;

public class ParseDate {

    public static void main(String args[]) {

        String day = null;
        String month = null;
        String year = null;
        String format = null;
        Scanner input = new Scanner(System.in);

        do {
            if (day == null) {
                System.out.println("Enter the day: ");
                day = input.nextLine();
            }
            if (month == null) {
                System.out.println("Enter the month: ");
                month = input.nextLine();
            }
            if (year == null) {
                System.out.println("Enter the year: ");
                year = input.nextLine();
            }

            try {
                format = formatDate(month, day, year);
            } catch (MonthException m) {
                System.err.println(month + " is not a valid month");
                month = null;
            } catch (DayException d) {
                System.err.println(day + " is not a valid day");
                day = null;
            } catch (YearException y) {
                System.err.println(year + " is not a valid year");
                year = null;
            }
        } while (format == null);
    }

    public static String formatDate(String month, String day, String year)
                    throws MonthException, DayException, YearException {
        String output = "Happy";

        int monthNum = 0;
        int dayNum = 0;
        int yearNum = 0;

        try {
            monthNum = Integer.parseInt(month);
            if (monthNum < 1 || monthNum > 12) {
                throw new MonthException("Invalid month. reenter.");
            }
        } catch (NumberFormatException exp) {
            throw new MonthException("Invalid month. reenter.");
        }
        try {
            yearNum = Integer.parseInt(year);
            if (yearNum < 1000 || yearNum > 3000) {
                throw new YearException("Invalid year. reenter.");
            }
        } catch (NumberFormatException exp) {
            throw new YearException("Invalid year. reenter.");
        }
        try {
            dayNum = Integer.parseInt(day);
            // You need to take into consideration the actual month,
            // but I'll leave that to you...
            if (dayNum < 1 || dayNum > 31) {
                throw new DayException("Invalid day. reenter.");
            }
        } catch (NumberFormatException exp) {
            throw new DayException("Invalid day. reenter.");
        }

        //other code here for converting date
        return output;
    }

    public static class MonthException extends Exception {

        public MonthException(String message) {
            super(message);
        }

    }

    public static class DayException extends Exception {

        public DayException(String message) {
            super(message);
        }

    }

    public static class YearException extends Exception {

        public YearException(String message) {
            super(message);
        }

    }
}

Now, frankly it would be simpler to validate each one individually, but that's me 坦率地说,现在单独验证每个对象会更简单,但这就是我

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

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