英文:
java use simpledateformat to parse a input String get ParseException, and just because of a space
问题
输入一个字符串,类似于要求的 SimpleDateFormat 格式,但会出现 ParseException。我进行了几次测试。如果我将“dd HH”之间的空格改为“dd-HH”,那么格式变为“yyyy-MM-dd-HH:mm:ss”,并且将会成功。
第二个测试是我直接写一个字符串,如下:
`String birthdays = "1998-08-12 12:12:12";`
并对其进行解析,同样会成功。
所以我的结论是我输入的空格与模式中的空格不同。我使用的是 IntelliJ。
SimpleDateFormat datef = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Scanner sc = new Scanner(System.in);
System.out.println("请输入您的生日。模式为:" +
"yyyy-MM-dd HH:mm:ss");
String birthday = sc.next();
Date date2 = datef.parse(birthday);
// String birthdays = "1998-08-12 12:12:12";
// Date date2 = datef.parse(birthdays); // 这将会成功
System.out.println(date2);
<details>
<summary>英文:</summary>
I input a string likes the SimpleDateFormat pattern asked, but it will be ParseException. I do several tests. If I change space between "dd HH" to "dd-HH", the pattern becomes "yyyy-MM-dd-HH:mm:ss", and it will be successful.
The second test is I write a string directly like
`String birthdays = "1998-08-12 12:12:12";`
and parse it, it will also successful.
so my conclusion is the space I input is not the same as the space in the pattern. what I used is IntelliJ.
SimpleDateFormat datef = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Scanner sc = new Scanner(System.in);
System.out.println("Please input your birthday. the pattern is " +
"yyyy-MM-dd HH:mm:ss");
String birthday = sc.next();
Date date2 = datef.parse(birthday);
// String birthdays = "1998-08-12 12:12:12";
// Date date2 = datef.parse(birthdays); //this will successful
System.out.println(date2);
</details>
# 答案1
**得分**: 1
代替使用 `sc.next()`,请使用 `sc.nextLine()`。
`sc.next()` 会找到第一个空格之前的字符串,但是 `nextLine()` 会接受包括空格在内的整个字符串。
那个问题并不是由于空格引起的。
<details>
<summary>英文:</summary>
Instead of using sc.next() use sc.nextLine()
sc.next() will find the first string till space but nextLine() will accept the entire string including space.
That issue is not because of the space.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论