2014-09-25 46 views
-1

這個程序是假設採取一個人的名字,性別和人數有一個字符串中的名稱和單獨的名稱,性別變成一個字符,並將人數與名稱變成一個int 。具有名稱的人數已經計算好了,我只需要將每個人分成正確的類別。 問題是代碼編譯但我得到一個NoSuchElementException錯誤。代碼編譯,但我得到NoSuchElementException錯誤

文件看起來是這樣的:

約翰,男,416

薩拉,F,414

邁克,男,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 2014-09-25 05:26:31

+0

線程「main」中的異常java.util.NoSuchElementException \t at java.util.StringTokenizer.nextToken(StringTokenizer.java:349) \t at NameYear。 (NameYear.java:44) \t at TopNames.main(TopNames.java:17) – ttt 2014-09-25 05:29:12

回答

0

您必須將分隔符設置爲逗號:

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

比它會工作。

如果您在使用StringTokenizer作爲

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

您的文字將被\t\n\r\f標記化不設置分隔符將設置爲\r\n

+0

@ttt請顯示對象'OneName' – Jens 2014-09-25 05:37:22

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日是你的字符串&二號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); 
    } 

希望它能幫助

相關問題