2017-10-14 85 views
1

用戶輸入格式爲XX/XX/XXXX的日期,並使用分隔符來挑選輸入中的整數,但我無法弄清楚如何在不將另一個/放在末尾的情況下獲取year變量的輸入。我該如何去爭取那一年的變數?爲什麼掃描儀不能在沒有/末的情況下選擇我的年份變量?

在此先感謝

package formatting_problem; 

import java.util.Scanner; 
public class DateFormatter { 
public static void main(String[] args) { 
    Integer day = 0; 
    Integer month = 0; 
    Integer year = 0; 
    Integer test = null; 
    Scanner input = new Scanner(System.in).useDelimiter("/"); 
    System.out.println("Enter a date in the format XX/XX/XXXX to be formatted to Month Day,Year"); 
    while (input.hasNext()){ 
     month = input.nextInt(); 
     day = input.nextInt(); 
     year = input.nextInt(); 
     System.out.println(); 
    } 

回答

2

我如何去獲得那年的變量?

你可以用String.split()

String tokens[] = input.split("/");  //where input is a String 
int month = Integer.parseInt(tokens[0]); 
int day = Integer.parseInt(tokens[1]); 
int year = Integer.parseInt(tokens[2]); 

注意:您可以只使用原始數據類型int,而不是他們的包裝類Integer的。


要回答你的問題,那是因爲你分配的分隔符只是一個正斜槓。在Java中,默認情況下,換行符也是分隔符之一。但是,在重新定義分隔符時,它被省略了。

爲了解決這個問題,包括換行符,以及:

Scanner input = new Scanner(System.in).useDelimiter("/|\\n"); 

您也可以刪除您while循環,只是:

int month = input.nextInt(); 
int day = input.nextInt(); 
int year = input.nextInt(); 
相關問題