gpt4 book ai didi

java - 使用 int 作为 GregorianCalendar 的输入,但无法继续扫描 JAVA

转载 作者:行者123 更新时间:2023-11-30 08:08:59 25 4
gpt4 key购买 nike

我试图编写一个代码来输入出生日期以返回当天的星期几,我使用输入流阅读器来获取我的输入

package testing;

import java.io.*;
import java.text.DateFormat;
import java.util.*;

public class theDayYouBorn {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

System.out.println("Please Input the Year You Born at : ");
int year1 = br.read();
System.out.println("Thank!, Please input the Month :");
int month1 = br.read();
System.out.println("Okay, last thing Please input the day : ");
int day1 = br.read();

GregorianCalendar gc = new GregorianCalendar(year1, month1, day1);
Date d1 = gc.getTime();
DateFormat df = DateFormat.getDateInstance();
String sd = df.format(d1);
String dayName = gc.getDisplayName(gc.DAY_OF_WEEK, gc.LONG,
Locale.getDefault());
System.out.println("The Day you born in was a " + sd
+ " and the day was " + dayName);

}
}

它让我只需输入第一个输入,然后运行它并生成一个随机日期,而不询问日期或月份

然后我尝试使用字符串作为输入并将它们转换为整数,它的工作......我改变了这一点:

System.out.println("Please Input the Year You Born at : ");
String year = br.readLine();
System.out.println("Thank!, Please input the Month :");
String preMonth = br.readLine();
System.out.println("Okay, last thing Please input the day : ");
String day = br.readLine();

int day1 = Integer.parseInt(day);
int month2 = Integer.parseInt(preMonth);
int year1 = Integer.parseInt(year);
int month1 = month2 - 1;

我试图理解为什么我无法扫描整数。

最佳答案

如果你看一下 documentation of read() method你会发现:

Reads a single character.

Returns:
The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached

因此每次调用read都会返回一个char(或者更准确地说,它在Unicode表中的数字表示形式如'a'97,或'1'49)。

例如,如果下面的代码

System.out.println("Please Input the Year You Born at : ");
System.out.println(br.read());
System.out.println(br.read());
System.out.println(br.read());
System.out.println(br.read());
System.out.println(br.read());
System.out.println(br.read());

我们将提供输入1987

Please Input the Year You Born at : 
1987[here we press enter]

在 Windows 操作系统上,我们最终会得到

49
57
56
55
13
10

代表

int -> char
-----------
49 -> '1'
57 -> '9'
56 -> '8'
55 -> '7'
13 -> '\r'
10 -> '\n'

br.readLine();的情况下不存在这样的问题,因为它的目的是将数据作为文本而不是二进制数据读取。

关于java - 使用 int 作为 GregorianCalendar 的输入,但无法继续扫描 JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30687153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com