2013-11-04 6 views
1

내 프로그램에서 다양한 날짜를 반복해야합니다. 나는이 프로그램을 자바로 작성하고 독자들과 약간의 경험을 쌓았지만 어떤 독자가이 작업을 가장 잘 수행 할 것인지 또는 다른 클래스가 더 잘 작동 하는지를 알지 못한다. 다음과 같이 날짜 형식으로 텍스트 파일에 입력 될 것이다 :입력 파일에서 변수를 만드는 방법

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

몇 가지 옵션이 있습니다.

스캐너를 사용하고 슬래시를 포함하도록 구분 기호를 설정할 수 있습니다. 당신의 int가 아닌 문자열로 값을 원하는 경우에, 다만 제안 alfasin로 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(); 
} 

당신은, 정규식을 사용할 수 있습니다 사용하지만, 당신은 단지 첫 번째와 마지막 공간을 일치시킬 수 있습니다이 경우는 오히려 간단하다.

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]); 
    ... 

OUTPUT

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

본질적으로 전체 날짜 중 하나의 큰 문자열을 만드는 대신 "시작"의 각 부분을 참조하여 월, 일, 연도를 얻을 수 있습니까? 또한 텍스트 파일의 각 줄을 읽는 데 독자를 사용할 수 있습니까? – Ctech45

+0

@Connor 내가 게시 한 코드에서'start [0]'은'1/1/2013'에서 "1"을, start [1]은 다른 "1"을,'start [2] 2013'. 따라서 문자열 배열 또는 문자열 매개 변수를 사용하여 이러한 값을 캡처 할 수 있습니다. – alfasin

+0

두 번째 질문에 대해서는 "스캐너"또는 "BufferedReader"를 사용하여 각 행을 읽은 다음 정규 표현식을 사용하는 구문 분석 부분을 적용 할 수 있습니다. – alfasin

관련 문제