Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何处理无效输入_Java - Fatal编程技术网

Java 如何处理无效输入

Java 如何处理无效输入,java,Java,有人能举个例子说明如何处理无效输入吗?我把键盘输入的逻辑搞错了。所以,我需要!或者将该循环放入一个我可以永远重用的方法中 package dayoftheyear; import java.util.Scanner; /** * * @author abdal */ public class DayOfTheYear { /** * Ask the user to enter a month, day, and year as integers * sep

有人能举个例子说明如何处理无效输入吗?我把键盘输入的逻辑搞错了。所以,我需要!或者将该循环放入一个我可以永远重用的方法中

package dayoftheyear;

import java.util.Scanner;

/**
 *
 * @author abdal
 */
public class DayOfTheYear {

    /**
     * Ask the user to enter a month, day, and year as integers
     * separated by spaces then display the number of the days since the
     * beginning of the year.
     * Don’t forget about leap year.
     * Sample: user inputs ‘3 1 2000’, output is ‘61’.
     * @param args Unused.
     */
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String enter = "A-z";
        int a=31;
        int b=1;


        boolean dateCheck;
        int month;
        int day;
        int year;

        do {
            System.out.print("Enter a valid month day year separated by spaces");
            if (s.hasNextInt()) {
                month= s.nextInt();
                day=s.nextInt();
                year=s.nextInt();
                if (month >= b && month <= a || day>=b && day<=a || year>=b) {
                    int numberOfDay = countDays(month, day, year);
                    System.out.println(+ month + "/" + day + "/" + year + " is a day number " 
                                + numberOfDay + " of that year");
                    dateCheck = true;
                } else {
                    System.out.println("Enter a valid month day year separated by spaces");
                    dateCheck = false;
                }
            } else {
                System.out.println("Not a date");
                month = 0;
                day=0;
                year=0;
                s.next();
                dateCheck = false;
            }
        } while (!dateCheck);

    /**
     * Get the number of days since the start of the year.
     * Declare a 12 element array and initialize it with the number of
     * days in each month.
     * @param month Month to count from.
     * @param day Day of the month to count to.
     * @param year The year to count from.
     * @return Days since the start of the given year.
     */
    } public static int countDays(int month, int day, int year) {
        int monthLength[] = {
            31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
        };
        int days = 0;
        if (isLeapYear(year) && month > 2) 
            days += 1;
        for (int i = 0; i < month - 1; i++) 
            days += monthLength[i];
        return days += day;
    }

    /**
     * Check if a year is a leap year.
     * @param year Year to check.
     * @return True if the year is a leap year.
     */

        public static boolean isLeapYear(int year) {
            if (year % 4 != 0) return false;
            else if (year % 100 != 0) return true;
            else return year % 400 == 0;
    }   
}

我认为下面的代码可以帮助您,如果您有任何问题,请发表评论

while(true) {
    try{
        System.out.print("Enter a valid month day year separated by spaces");
        month= s.nextInt();
        day=s.nextInt();
        year=s.nextInt();
        if (month >= 1 && month <= 12 || day>=1 && day<=31 || year>=1) {
            System.out.println(+ month + "/" + day + "/" + year + " is a day number "+ " of that year");
            break;
        } else {
            System.out.println("Enter a valid month day year separated by spaces");
        }
    } catch(InputMismatchException e) {
        System.out.println("Enter a valid month day year separated by spaces");
    }
    s.next();
}

我认为下面的代码可以帮助您,如果您有任何问题,请发表评论

while(true) {
    try{
        System.out.print("Enter a valid month day year separated by spaces");
        month= s.nextInt();
        day=s.nextInt();
        year=s.nextInt();
        if (month >= 1 && month <= 12 || day>=1 && day<=31 || year>=1) {
            System.out.println(+ month + "/" + day + "/" + year + " is a day number "+ " of that year");
            break;
        } else {
            System.out.println("Enter a valid month day year separated by spaces");
        }
    } catch(InputMismatchException e) {
        System.out.println("Enter a valid month day year separated by spaces");
    }
    s.next();
}

由于日期格式在现实世界中不会发生变化,所以应该使用一些硬编码。通常建议将问题分为几种方法

您可以向类中添加以下方法:

private static boolean validDate(int month, int day, int year) {
    if (year < 1) {
        return false; // no B.C.
    }
    if (month > 1 && month < 13) {
        if (month == 2) { // handle February
            return validFeb(day, year);
        } else if (month % 2 == 1 && month < 8 
                || month % 2 == 0 && month >= 8) { // 31-day months
            return valid31(day);
        } else { // 30 day months
            return valid30(day);
        }
    }

    return false;
}

由于日期格式在现实世界中不会发生变化,所以应该使用一些硬编码。通常建议将问题分为几种方法

您可以向类中添加以下方法:

private static boolean validDate(int month, int day, int year) {
    if (year < 1) {
        return false; // no B.C.
    }
    if (month > 1 && month < 13) {
        if (month == 2) { // handle February
            return validFeb(day, year);
        } else if (month % 2 == 1 && month < 8 
                || month % 2 == 0 && month >= 8) { // 31-day months
            return valid31(day);
        } else { // 30 day months
            return valid30(day);
        }
    }

    return false;
}
替换

if (month >= b && month <= a || day>=b && day<=a || year>=b)
更新1:以下情况也适用于2月份

if ((month == 2 && day >= 1 && day <= 28 && year >= 1 && !isLeapYear(year))
        || (month == 2 && day >= 1 && day <= 29 && year >= 1 && isLeapYear(year))
        || (month != 2 && month >= 1 && month <= 12 && day >= 1 && day <= 31 && year >= 1)) 
更新2:下面的代码解决了评论中提出的所有问题

int monthLength[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if ((month == 2 && day >= 1 && day <= 28 && year >= 1 && !isLeapYear(year))
        || (month == 2 && day >= 1 && day <= 29 && year >= 1 && isLeapYear(year))
        || (month != 2 && month >= 1 && month <= 12 && day >= 1 && day <= monthLength[month-1] && year >= 1))
替换

if (month >= b && month <= a || day>=b && day<=a || year>=b)
更新1:以下情况也适用于2月份

if ((month == 2 && day >= 1 && day <= 28 && year >= 1 && !isLeapYear(year))
        || (month == 2 && day >= 1 && day <= 29 && year >= 1 && isLeapYear(year))
        || (month != 2 && month >= 1 && month <= 12 && day >= 1 && day <= 31 && year >= 1)) 
更新2:下面的代码解决了评论中提出的所有问题

int monthLength[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if ((month == 2 && day >= 1 && day <= 28 && year >= 1 && !isLeapYear(year))
        || (month == 2 && day >= 1 && day <= 29 && year >= 1 && isLeapYear(year))
        || (month != 2 && month >= 1 && month <= 12 && day >= 1 && day <= monthLength[month-1] && year >= 1))

谢谢,我更新了我的程序,它正在工作

        public static void main(String[] args) {
    Scanner s = new Scanner(System.in);

    int year = 0;
    int month = 0;
    int day = 0;
    boolean dateCheck;
    do {
    System.out.print("Enter a valid month day year separated by spaces\n");
    if (s.hasNextInt()) month = s.nextInt();
        else s.next();
    if (s.hasNextInt()) day = s.nextInt(); 
        else s.next();
    if (s.hasNextInt()) year = s.nextInt(); 
        else s.next();

    int numberOfDaysSinceStart = 0;
    if (month >= 1 && month <= 12 && day >= 1 && day <= 31 && year >= 1) {
        dateCheck = true;
        numberOfDaysSinceStart = countDays(month, day, year);
        System.out.println(month + "/" + day + "/" + year + " is a day number "
            + numberOfDaysSinceStart + " of that year");
    } else {
        dateCheck = false;
    }
} while (!dateCheck);

/**
 * Get the number of days since the start of the year.
 * Declare a 12 element array and initialize it with the number of
 * days in each month.
 * @param month Month to count from.
 * @param day Day of the month to count to.
 * @param year The year to count from.
 * @return Days since the start of the given year.
 */
} public static int countDays(int month, int day, int year) {
    int monthLength[] = {
        31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };
    int days = 0;
    if (isLeapYear(year) && month > 2) 
        days += 1;
    for (int i = 0; i < month - 1; i++) 
        days += monthLength[i];
    return days += day;
}

/**
 * Check if a year is a leap year.
 * @param year Year to check.
 * @return True if the year is a leap year.
 */
public static boolean isLeapYear(int year) {
    if (year % 4 != 0) return false;
    else if (year % 100 != 0) return true;
    else return year % 400 == 0;
}

}谢谢,我更新了我的程序,它正在运行

        public static void main(String[] args) {
    Scanner s = new Scanner(System.in);

    int year = 0;
    int month = 0;
    int day = 0;
    boolean dateCheck;
    do {
    System.out.print("Enter a valid month day year separated by spaces\n");
    if (s.hasNextInt()) month = s.nextInt();
        else s.next();
    if (s.hasNextInt()) day = s.nextInt(); 
        else s.next();
    if (s.hasNextInt()) year = s.nextInt(); 
        else s.next();

    int numberOfDaysSinceStart = 0;
    if (month >= 1 && month <= 12 && day >= 1 && day <= 31 && year >= 1) {
        dateCheck = true;
        numberOfDaysSinceStart = countDays(month, day, year);
        System.out.println(month + "/" + day + "/" + year + " is a day number "
            + numberOfDaysSinceStart + " of that year");
    } else {
        dateCheck = false;
    }
} while (!dateCheck);

/**
 * Get the number of days since the start of the year.
 * Declare a 12 element array and initialize it with the number of
 * days in each month.
 * @param month Month to count from.
 * @param day Day of the month to count to.
 * @param year The year to count from.
 * @return Days since the start of the given year.
 */
} public static int countDays(int month, int day, int year) {
    int monthLength[] = {
        31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };
    int days = 0;
    if (isLeapYear(year) && month > 2) 
        days += 1;
    for (int i = 0; i < month - 1; i++) 
        days += monthLength[i];
    return days += day;
}

/**
 * Check if a year is a leap year.
 * @param year Year to check.
 * @return True if the year is a leap year.
 */
public static boolean isLeapYear(int year) {
    if (year % 4 != 0) return false;
    else if (year % 100 != 0) return true;
    else return year % 400 == 0;
}

}

您可以永远添加边缘案例。有一个原因,为什么与时间相关的计算被外包给一些可怜的灵魂编写的图书馆,而这些灵魂却被付钱试图涵盖所有这些计算。Java有这样的内置功能,请看Java.util.Calendar Gregorian实现。 您将其设置为年/月/日,如果在尝试获得结果时出现任何错误,它将吐出异常

Calendar c = Calendar.getInstance();
c.set(year, month, day);
try {
    c.getTime();
} catch (Exception e) {
    // wrong date format
}

您可以永远添加边缘案例。有一个原因,为什么与时间相关的计算被外包给一些可怜的灵魂编写的图书馆,而这些灵魂却被付钱试图涵盖所有这些计算。Java有这样的内置功能,请看Java.util.Calendar Gregorian实现。 您将其设置为年/月/日,如果在尝试获得结果时出现任何错误,它将吐出异常

Calendar c = Calendar.getInstance();
c.set(year, month, day);
try {
    c.getTime();
} catch (Exception e) {
    // wrong date format
}


为什么不java.time.Year.ofyear.isLeap;就像为什么不java.time.Year.ofyear.isLeap;比如,如果日期无效,如何使系统不停止并不断要求用户输入有效日期。系统在几次尝试后停止。例如,如果用户不断输入无效数据,如cat或dog 2000,我希望程序继续要求用户输入一个有效日期。@malekiamir 2 30 2020不应该是一个有效日期。2月有29天是那一年。我仍然得到输入2 30 2020的无效结果:输入一个由空格分隔的有效月-日-年。2 30 2020 2/30/2020是那一年的天数。这不应被视为有效日期。@Pajacar123很抱歉,请将if语句更改为:if month>=1&&month=1&&day=1990如果日期无效,如何使系统不停止并继续要求用户输入有效日期。系统在几次尝试后停止。例如,如果用户不断输入无效数据,如cat或dog 2000,我希望程序继续要求用户输入一个有效日期。@malekiamir 2 30 2020不应该是一个有效日期。2月有29天是那一年。我仍然得到输入2 30 2020的无效结果:输入一个由空格分隔的有效月-日-年。2 30 2020 2/30/2020是那一年的天数。这不应被视为有效日期。@Pajacar123很抱歉,将if语句更改为:if month>=1&&month=1&&day=19902 30 2020不应该是有效日期2月有29天渴望我在6 31 2020年6月有一个错误应该有30天输入一个有效的月-日-年,用空格分隔6 31 2020 6/31/2020是该年的第183天很容易错过一些长的日期表达式2 30 2020不应该是一个有效日期2月有29天渴望我在6 31 2020 6月有一个错误应该有30输入一个有效的月-日-年用空格隔开6 31 2020 6/31/2020是该年的日期数183很容易错过一些长表达式的内容,因为它工作不正常。你应该非常小心日期,你必须考虑每一种情况。当你输入2302020,你会得到一个结果,说这是一年中的第61天。然而,二月没有30天。试试我的解决办法。旁注:您可能不应该发布您自己问题的答案,除非这是您在开始时的意图。为了征求您的意见,我确实使用了您的解决方案,但当我输入2302020时,我仍然得到结果,显示它是一年中的第61天。您可能错过了一些内容。我得到了正确的结果。请尝试再次复制。输入由空格2 30 2020分隔的有效月-日-年输入由空格2 29 2020分隔的有效月-日-年2/29/2020是该年的第60天-它工作不正常。你应该非常小心日期,你必须考虑每一种情况。当你
输入2302020,结果显示这是一年中的第61天。然而,二月没有30天。试试我的解决办法。旁注:您可能不应该发布您自己问题的答案,除非这是您在开始时的意图。为了征求您的意见,我确实使用了您的解决方案,但当我输入2302020时,我仍然得到结果,显示它是一年中的第61天。您可能错过了一些内容。我得到了正确的结果。请尝试再次复制。输入由空格2 30 2020分隔的有效月-日-年输入由空格2 29 2020分隔的有效月-日-年2/29/2020是该年的天数60
Calendar c = Calendar.getInstance();
c.set(year, month, day);
try {
    c.getTime();
} catch (Exception e) {
    // wrong date format
}