Java逻辑错误 - 如果语句

时间:2015-10-26 02:21:26

标签: java date

我需要测试String输入日期(mm / dd / yyyy)是否有效。标准是普通日历的标准,特别是我的问题,月份需要在1到12之间。无论出于什么原因,如果我输入应该是有效的月份,并且输入本身应该基于我的if语句为真,我的程序正在将其视为错误。

例如,如果我输入01/01/2000,则int月份将= 1.因此月份大于0且小于13.但是程序将其读作false并且我无法弄清楚原因。感谢

import java.util.Scanner;

public class C3PP4_Benjamin_Crosta_CTIM15701 {
    public static void main(String[] args) {
        String inputDate, monthString, dayString, yearString;
        boolean validMonth, leapYear;
        Scanner keyboard = new Scanner(System. in );

        //user input
        System.out.println("Please enter date. (mm/dd/yyyy)");
        inputDate = keyboard.nextLine();

        //PROCESSING
        monthString = inputDate.substring(0, 2);
        dayString = inputDate.substring(3, 5);
        yearString = inputDate.substring(6, 10);

        //String to int conversion
        int month = Integer.parseInt(monthString);
        int day = Integer.parseInt(dayString);
        int year = Integer.parseInt(yearString);

        //months 
        if ((month > 0 && month < 13)) validMonth = true;
        else validMonth = false;
        System.out.println("Your date is invalid because the month you entered does not exist.");
    }
}

1 个答案:

答案 0 :(得分:2)

if (month > 0 && month < 13){
validMonth = true;
} else {
validMonth = false;
System.out.println("Your date is invalid because the month you entered does not exist.");
}

如果你不使用花括号,它只会在下面执行一行,也可以在if语句中使用单括号

您也可以使用拆分(&#39; /&#39;):

String date = "01/01/1970";
String[] split = date.split("/");
int day = Integer.parseInt(split[0]);
int month = Integer.parseInt(split[1]);
int year = Integer.parseInt(split[2]);