Java 从用户处获取日期(mm/dd/yyyy),检查是否有效,打印日期(月、日、年)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21473086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting date from user (mm/dd/yyyy), checking to see if it is valid, printing date (month, day year)
提问by user3256045
I'm having a hard time with a few things. I'm fairly new to Java and I can't figure out how to read the first two digits to determine 08 or 09 due to the Octal digits. Also I'm getting a return of null, 1, 199 which don't need to be there. Help would be appreciated.
我有几件事很难受。我对 Java 还很陌生,由于八进制数字,我无法弄清楚如何读取前两位数字来确定 08 或 09。此外,我得到了 null, 1, 199 的回报,这不需要在那里。帮助将不胜感激。
import java.util.*;
public class Dates {
public static void main(String[] args) {
String January,February, March, April, May, June, July,
August, September,October, November, December, month;
January = February = March = April = May = June = July =
August = September = October = November = December = month = null;
Scanner myScanner = new Scanner(System.in);
System.out.print("Enter date in the format mm/dd/yyyy: ");
String input = myScanner.next();
String months = input.substring(0,1);
int monthInt = Integer.parseInt(months);
if (monthInt == 01){
month = January;
}
else if (monthInt == 02){
month = February;
}
else if (monthInt == 03){
month = March;
}
else if (monthInt == 04){
month = April;
}
else if (monthInt == 05){
month = May;
}
else if (monthInt == 06){
month = June;
}
else if (monthInt == 07){
month = July;
}
else if (monthDouble == 08){
month = August;
}
else if (monthDouble == 09){
month = September;
}
else if (monthInt == 10){
month = October;
}
else if (monthInt == 11){
month = November;
}
else if (monthInt == 12){
month = December;
}
else {
System.out.println("Invalid Month");
}
String days = input.substring(3,4);
int daysInt = Integer.parseInt(days);
if ((daysInt <= 31) && (monthInt == 1 || monthInt == 3 || monthInt ==
5 || monthInt == 7 || monthInt == 8 || monthInt == 10 || monthInt
== 12)){
daysInt = daysInt;
}
else if ((daysInt <= 30) && (monthInt == 4 || monthInt == 6 || monthInt
== 9 || monthInt == 11)){
daysInt = daysInt;
}
else if ((daysInt <= 28) && (monthInt == 2)){
daysInt = daysInt;
}
else
System.out.println("Invalid Day");
String year = input.substring(6,9);
int yearInt = Integer.parseInt(year);
if (yearInt >= 1900 && yearInt <= 2014) {
yearInt = yearInt;
}
else {
System.out.println("Year should be between 1900 and 2014");
}
String checkSlash = input.substring(2);
char slash = checkSlash.charAt(0);
if (slash == '/')
slash = slash;
else
System.out.println("Invalid format. Use mm/dd/yyyy");
System.out.println(month + " " + daysInt + ", " + year);
}
}
回答by Christian
Java will consider numbers with leading zeros as octals, and a digit in octal base cannot be larger than 7. You will get an error if you try to use 08
, 09
. You could use String
s instead:
Java将考虑数字与前导零的八进制和八进制基地的数字不能大于7,如果你试图使用你会得到一个错误08
,09
。您可以使用String
s 代替:
if (months.equals("01"))
...
And I think (since you want to compare with "01", "02", ...) you should use substring(0,2)
:
我认为(因为您想与“01”、“02”、...进行比较)您应该使用substring(0,2)
:
String months = input.substring(0,2);
回答by Scary Wombat
try this for a simpler way
试试这个更简单的方法
String strDate = "11/29/2009";
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date dateStr = formatter.parse(strDate);
回答by Makoto
There are vastly better ways to do this, most notably using even Java's Date
and SimpleDateFormat
classes, but if you must know...
有很多更好的方法可以做到这一点,最显着的是使用 JavaDate
和SimpleDateFormat
类,但如果你必须知道......
Don't include the leading zero on the integers. You're not going to be reading or otherwise dealing withoctal values. January is the first month, and it's much more straightforward to represent it as 1
.
不要在整数上包含前导零。您不会阅读或以其他方式处理八进制值。一月是第一个月,将其表示为1
.
I'll give you an alternative, if you really don't want to use SimpleDateFormat
. Consider that we know the values all fall in an integral range (that is, they're all going to be less than 2.1 billion). If we let the Integer
class do the work of parsing the value for us, then we can do this in much less code.
如果您真的不想使用SimpleDateFormat
. 考虑到我们知道所有值都在一个整数范围内(即它们都将小于 21 亿)。如果我们让Integer
类为我们完成解析值的工作,那么我们可以用更少的代码来完成这项工作。
Further to that, we don't need to worry about weird substrings (which, by the way, yours will only grab the first element - which is problematic).
此外,我们不需要担心奇怪的子字符串(顺便说一下,你的子字符串只会抓取第一个元素 - 这是有问题的)。
Let's use the String#split()
method and break up the input string on forward slashes.
让我们使用该String#split()
方法并在正斜杠上拆分输入字符串。
String[] brokenInput = input.split("/");
Now we're given by our format and convention that the month is in brokenInput[0]
, the day in brokenInput[1]
, and the year in brokenInput[2]
.
现在,我们的格式和约定给出了月份在 中brokenInput[0]
,日在 中brokenInput[1]
,年在 中brokenInput[2]
。
Parsing is easy then:
解析很容易:
Integer monthInt = Integer.parseInt(brokenInput[0]);
Integer daysInt = Integer.parseInt(brokenInput[1]);
Integer yearInt = Integer.parseInt(brokenInput[2]);
回答by MadProgrammer
I'm going to assume that there is a reason why you are doing this the long way.
我将假设您长期这样做是有原因的。
To start with, removing the leading 0
of your int
values when checking the month, they convert the value to octal, which you don't need...
首先,去除导致0
你的int
检查一个月的时候值,它们值转换为八进制,你不需要......
if (monthInt == 1) {
month = January;
} else if (monthInt == 2) {
month = February;
} else if (monthInt == 3) {
month = March;
} else if (monthInt == 4) {
month = April;
} else if (monthInt == 5) {
month = May;
} else if (monthInt == 6) {
month = June;
} else if (monthInt == 7) {
month = July;
} else if (monthInt == 8) {
month = August;
} else if (monthInt == 9) {
month = September;
} else if (monthInt == 10) {
month = October;
} else if (monthInt == 11) {
month = November;
} else if (monthInt == 12) {
month = December;
} else {
System.out.println("Invalid Month");
}
This...
这个...
String months = input.substring(0, 1);
Will get the first character of the input, but you've asked the user for mm/dd/yyyy
, which suggests that you want a two digit value for the month and day...besides, what happens if they type in 12
?
将获得输入的第一个字符,但您已经向用户询问了mm/dd/yyyy
,这表明您想要月和日的两位数值......此外,如果他们输入 ,会发生什么12
?
Instead you could use String[] parts = input.split("/");
to split the input
String
on the /
delimiter, this (if the input is valid) will give you three elements, one each part of the date value.
相反,你可以使用String[] parts = input.split("/");
分割input
String
的/
分隔符,这(如果输入有效)会给你三个要素,一个日期值的各个部分。
Then you can use...
然后你可以用...
int monthInt = Integer.parseInt(parts[0]);
//...
int daysInt = Integer.parseInt(parts[1]);
//...
int yearInt = Integer.parseInt(parts[2]);
To convert the individual elements.
转换单个元素。
This raises the question that you should probably validate the input value in some meaningful way BEFORE you try and split it.
这提出了一个问题,即在尝试拆分输入值之前,您可能应该以某种有意义的方式验证输入值。
The month values are all null
月份值都是 null
String January, February, March, April, May, June, July,
August, September, October, November, December, month;
January = February = March = April = May = June = July
= August = September = October = November = December = month = null;
Which basically means you output will always start with null
. You actually need to assign these some meaningful value.
这基本上意味着您的输出将始终以null
. 您实际上需要为这些分配一些有意义的值。
I'll also parrot what every body else has said, unless you have a really good reason to do otherwise, I'd be using Calendar
and some kind of DateFormat
to do all this...
我也会模仿其他人所说的话,除非你有很好的理由不这样做,否则我会使用Calendar
某种方式DateFormat
来做这一切......
Updated with a (slightly over the top) example
更新了一个(略高于顶部)示例
This basically takes your idea and use SimpleDateFormat
and Calendar
to perform the actual checking of the input, for example...
这基本上需要您的想法和使用SimpleDateFormat
并Calendar
执行输入的实际检查,例如......
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Dates {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Date (mm/dd/yyyy):");
String input = kb.nextLine();
// This is a little excessive, but does a pre-check of the basic
// format of the date. It checks for a strict adhereance to
// the nn/nn/nnnn format. This might not be required as
// SimpleDateFormat can actually be configured to be lient in it's
// parsing of values
if (input.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")) {
try {
// Parse the String input to a Date object
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date date = sdf.parse(input);
// Create a Calendar, going to use this to compare the resulting
// Date value, as the parser will auto correct the input
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// Split the basic input along the / delimeter
String parts[] = input.split("/");
boolean valid = true;
// Check each part to make sure it matches the components of the date
if (Integer.parseInt(parts[0]) != cal.get(Calendar.MONTH) + 1) {
valid = false;
System.out.println(parts[0] + " is not a valid month");
}
if (Integer.parseInt(parts[1]) != cal.get(Calendar.DATE)) {
valid = false;
System.out.println(parts[1] + " is not a valid day of the month");
}
if (Integer.parseInt(parts[2]) != cal.get(Calendar.YEAR)) {
valid = false;
System.out.println(parts[2] + " is not a valid year");
}
if (valid) {
// Print the result...
System.out.println(new SimpleDateFormat("MMMM dd, yyyy").format(date));
}
} catch (ParseException ex) {
System.out.println("Unable to parse " + input + "; invalid format");
}
} else {
System.out.println("Invalid format");
}
}
}