2014-04-01 4 views
0

다양한 데이터 유형의 파일을 읽는 프로그램을 작성 중입니다. 내가 만든 여러 배열에 파일에서 데이터를 전달하려고합니다.InputMismatchException 입력 스캐너를 사용할 때

샘플 파일의 부분 그러나 나는

Name Age Country Year Closing Date Sport Gold Silver Bronze Total 

Joe Max 24 Algeria 2012 8/12/2012 Athletics 1 0 0 1 

Tom Lan 27 United States 2008 8/24/2008 Rowing 0 1 0 1 

내 코드 컴파일 (마지막/첫 번째 이름과 국가 간 줄 바꿈에 대한 이중 간격. 범주 탭입니다 사이에 화이트 스페이스,하지만 공백은 공백이됩니다) InputMismatchException를 취득합니다. 각 줄의 끝에는 계속되는 탭이 없다는 사실을 다루는 지 궁금합니다. 아무도 이것을 통해 나를 도울 수 있습니까?

public static void main(String[] args) { 
Scanner console = new Scanner(System.in); 
intro(); 

Scanner input1 = null; 
Scanner input2 = null; 
int lineCount = 0; 

try { 
    input1 = new Scanner(new File("olympicstest.txt")); 

} 
catch (FileNotFoundException e) { 
    System.out.println("Invalid Option"); 
    System.exit(1); 
} 

while (input1.hasNextLine()) { 
    lineCount++; 
    input1.nextLine(); 
} 

lineCount = lineCount - 1; 

String[] country = new String[lineCount]; 
int[] totalMedals = new int[lineCount]; 
String[] name = new String[lineCount]; 
int[] age = new int[lineCount]; 
int[] year = new int[lineCount]; 
String[] sport = new String[lineCount]; 

try { 
    input2 = new Scanner(new File("olympicstest.txt")); 
    input2.useDelimiter("\t"); 
} 
catch (FileNotFoundException e) { 
    System.out.println("Invalid Option"); // not sure if this line is needed 
    System.exit(1); // not sure if this line is needed 
}   

String lineDiscard = input2.nextLine(); 
for (int i = 0; i < lineCount; i++) { 
    name[i] = input2.next(); 
    age[i] = input2.nextInt(); 
    country[i] = input2.next(); 
    year[i] = input2.nextInt(); 
    input2.next(); // closing ceremony date 
    sport[i] = input2.next(); 
    input2.nextInt(); // gold medals 
    input2.nextInt(); // silver medals 
    input2.nextInt(); // bronze medals 
    totalMedals[i] = input2.nextInt(); 
} 

} 
+0

당신은 그것이 출력, 그 입력을 의미하지 않습니까? –

+0

정확합니다. 그것은 입력을 읽어야합니다. 지금 고치고있어. – Rivers31334

답변

1

예를 특정 구분 기호를 설정할 때, 불행하게도 그것은 당신의 .next() 문으로 잘 재생되지 않는 별도의 값으로 사용되는 유일한 구분된다, 그래서 당신도 할 수 있습니다 탭 (\t)을 각 행의 끝에 추가하거나 \t\n을 모두 구분 기호 "[\t\n]"으로 설정할 수 있습니다. 탭과 공백 문자는 종종 시각적 관점과 구별하기가 쉽지 않으므로 CSV 형식을 사용하고 모든 값을 쉼표로 구분하는 것을 선호합니다.

1

예, 문제의 원인에 대해 올바르게 알고 있습니다. 해결책은 탭과 줄 바꿈을 모두 허용하는 useDelimiter 호출에서 정규식을 사용하는 것입니다. 그래서 당신이 할 것 :

input2.useDelimiter("[\t\n]"); 

Explanation of the regex

관련 문제