2015-06-06 19 views
1

我試圖做的代碼輸入出生日期,讓那一天的一週的迴天,我使用的輸入流閱讀讓我輸入使用int值作爲GregorianCalendar的輸入,但我不能夠繼續掃描JAVA

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; 

我試圖理解爲什麼我不能夠掃描整數。

+2

請閱讀本:(https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#read%28%29)的'讀()'的JavaDoc]: *讀取單個字符。* – Tom

回答

1

如果您在documentation of read() method看一看,你會發現:

讀取單個字符。

返回
讀取的字符,爲整數0〜65535(0x00-0xffff),或-1,如果流的末尾,已達到

所以每個呼叫的範圍的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();情況存在。