2014-09-25 3 views
-1

이 프로그램은 사람 이름, 성별 및 사람의 수를 문자열, 성별로 분리 한 이름과 이름이있는 사람들의 수를 int로 취하는 것으로 가정합니다 . 이름을 가진 사람의 수는 이미 계산되어 있습니다. 각 카테고리를 올바른 카테고리로 구분하면됩니다. 문제는 코드가 컴파일되지만 NoSuchElementException 오류가 발생합니다.코드가 컴파일되지만 NoSuchElementException 오류가 발생합니다.

존, M, 416

사라, F, 414

마이크, M, 413

케이트, F, 413

ArrayList<OneName> oneName = new ArrayList<OneName>(); 
    while(sc.hasNextLine()) 
    { 

    // read a line from the input file via sc into line 
     line = sc.nextLine(); 
     String[] fields =line.split(","); 


     StringTokenizer stk = new StringTokenizer(line); 
     String name = stk.nextToken(); 
     char sex = stk.nextToken().charAt(0); 
     int count = Integer.parseInt(stk.nextToken()); 


     OneName list = new OneName(name, sex, count); 

     oneName.add(list);  


    } 
    String personSex = oneName.get(0).getName(); 
    System.out.println(personSex); 
    } 
:

파일은 다음과 같습니다

+0

당신이 당신의 전체 오류 로그를 제공하시기 바랍니다 것입니다 도움이 희망? – Simmant

+0

스레드 "main"의 예외 java.util.NoSuchElementException \t의 java.util.StringTokenizer.nextToken (StringTokenizer.java:349) \t at NameYear. (NameYear.java:44) \t at TopNames.main (TopNames.java:17) – ttt

답변

0

구분 기호를 쉼표로 설정해야합니다.

StringTokenizer stk = new StringTokenizer(line,","); 

이상 작동합니다.

당신이 당신의 텍스트가 \t\n\r\f에 의해 토큰 화합니다 StringTokenizer

StringTokenizer stk = new StringTokenizer("John,M,416"); 

로 사용하는 경우 당신이 \r\n

+0

@ttt 'OneName' 개체를 보여주세요. – Jens

0

로 설정됩니다 구분 기호를 설정하지 않으면. 따라서 stk.nextToken()John,M,416을주고, stk.nextToken()을 다시 부르면 NoSuchElementException이됩니다.

예 :

StringTokenizer stk = new StringTokenizer("John,M,416"); 
System.out.println(stk.nextToken()); 
System.out.println(stk.nextToken()); 

아웃 넣어 :

John,M,416 
Exception in thread "main" java.util.NoSuchElementException... 

그래서 사용하셔야합니다 StringTokenizer

StringTokenizer stk = new StringTokenizer("John,M,416",","); 
while (stk.hasMoreElements()){ 
    System.out.println(stk.nextToken()); 
} 

는 이제 아웃

John 
M 
416 
를 넣어 다음과 같이

코드에서 오류는 어디에 있습니까?

StringTokenizer stk = new StringTokenizer(line); 
String name = stk.nextToken(); // this line is ok 
char sex = stk.nextToken().charAt(0); // ohh this one cause the issue 
0

당신은 StringTokenizer 1 구문 분석 할 필요가 당신의 문자열 & 2 regix입니다 함께 두 개의 매개 변수를 전달해야합니다.

ArrayList<OneName> oneName = new ArrayList<OneName>(); 
     while(sc.hasNextLine()) 
    { 

    // read a line from the input file via sc into line 
     line = sc.nextLine(); 
     String[] fields =line.split(","); 


     StringTokenizer stk = new StringTokenizer(line,","); 
     String name = stk.nextToken(); 
     char sex = stk.nextToken().charAt(0); 
     int count = Integer.parseInt(stk.nextToken()); 


     OneName list = new OneName(name, sex, count); 

     oneName.add(list);  


    } 
    String personSex = oneName.get(0).getName(); 
    System.out.println(personSex); 
    } 

관련 문제