2013-11-04 29 views
1

在我的程序中,我需要遍歷各種日期。我正在用java編寫這個程序,並且對讀者有一些經驗,但是我不知道哪個讀者會最好地完成這個任務,或者如果另一個班級會更好地工作。 的日期將被輸入到一個文本文件中的格式如下:如何從輸入文件創建變量

1/1/2013 to 1/7/2013 
1/8/2013 to 1/15/2013 

或者這樣的一些東西。我需要將每個日期範圍分解成6個循環的局部變量,然後將它們更改爲下一個循環。這些變量將被編碼,例如:

private static String startingMonth = "1"; 
    private static String startingDay = "1"; 
    private static String startingYear = "2013"; 
    private static String endingMonth = "1"; 
    private static String endingDay = "7"; 
    private static String endingYear = "2013"; 

我想可以這樣做創建幾個分隔符查找,但我不知道,這將是最簡單的方法。我一直在尋找this的幫助,但似乎找不到相關答案。什麼是最好的方式去做這件事?

+0

我建議你看看'SimpleDateFormat'類。也許你可以用'parse'方法做些什麼。 –

回答

0

有幾種選擇。

您可以使用掃描儀,並將分隔符設置爲包含斜線。如果你想要的值做爲整數,而不是字符串,只需使用sc.nextInt()

Scanner sc = new Scanner(input).useDelimiter("\\s*|/"); 
// You can skip the loop to just read a single line. 
while(sc.hasNext()) { 
    startingMonth = sc.next(); 
    startingDay = sc.next(); 
    startingYear = sc.next(); 
    // skip "to" 
    sc.next() 
    endingMonth = sc.next(); 
    endingDay = sc.next(); 
    endingYear = sc.next(); 
} 

您可以使用正則表達式,如alfasin建議,但這種情況是相當簡單,所以你可以匹配的第一個和最後空間。

String str = "1/1/2013 to 1/7/2013"; 
String startDate = str.substring(0,str.indexOf(" ")); 
String endDate = str.substring(str.lastIndexOf(" ")+1);¨ 
// The rest is the same: 
String[] start = startDate.split("/"); 
System.out.println(start[0] + "-" + start[1] + "-" + start[2]); 
String[] end = endDate.split("/"); 
System.out.println(end[0] + "-" + end[1] + "-" + end[2]); 
0
String str = "1/1/2013 to 1/7/2013"; 
    Pattern pattern = Pattern.compile("(\\d+/\\d+/\\d+)"); 
    Matcher matcher = pattern.matcher(str); 
    matcher.find(); 
    String startDate = matcher.group(); 
    matcher.find(); 
    String endDate = matcher.group(); 
    String[] start = startDate.split("/"); 
    System.out.println(start[0] + "-" + start[1] + "-" + start[2]); 
    String[] end = endDate.split("/"); 
    System.out.println(end[0] + "-" + end[1] + "-" + end[2]); 
    ... 

輸出

1-1-2013 
1-7-2013 
+0

實質上,我可以引用「開始」的每個部分來獲取月份,日期,年份,而不是創建整個日期的一個大字符串?另外,我可以使用閱讀器閱讀文本文件的每一行嗎? – Ctech45

+0

@Connor在我發佈的代碼中,'start [0]'從'1/1/2013'開始保存「1」,'start [1]'保持另一個「1」並且'start [2] 2013'。所以你可以使用字符串數組或字符串參數來捕獲這些值。 – alfasin

+0

至於你的第二個問題,是的,你可以使用'Scanner'或'BufferedReader'讀取每一行,然後應用使用正則表達式的解析部分。 – alfasin