簡體   English   中英

java.net項目中StringTokenizer中的錯誤

[英]java Project with error in StringTokenizer

我制作了一個涉及StringTokenizer的Java項目,我使用了文件FemaleCoursesElec.csv,該文件用逗號分隔,然后用它填充array1,但是有一個問題,我不知道它是什么?

這是課程:

 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package shakeelprojectmain; /** * * @author lenovo */ import java.util.*; import java.io.*; public class ArrayOfCourses { public String[][] getAllCourses() throws IOException { String[][] array1 = new String[getRow()][getCol()]; int i = 0; String str; File file = new File("FemaleCoursesElec.csv"); Scanner in = new Scanner(file); while(in.hasNext()) { str = in.nextLine(); StringTokenizer token = new StringTokenizer(str,","); while(token.hasMoreTokens()) { for (int j = 0 ; j < getCol() ; j++) { array1[i][j] = token.nextToken(); } } i++; } in.close(); return array1; } /** * * @return * @throws java.io.IOException */ public int getRows() throws IOException { int row = 0; File file = new File("FemaleCoursesElec.csv"); Scanner in = new Scanner(file); while(in.hasNext()) { in.nextLine(); row++; } in.close(); return row; } public int getCol() throws IOException { int col = 0; File file = new File("FemaleCoursesElec.csv"); Scanner in = new Scanner(file); String str = in.nextLine(); StringTokenizer token; token = new StringTokenizer(str,"," ); while(token.hasMoreTokens()) { token.nextToken(); col++; } in.close(); return col; } private int getRow() throws IOException { int row = 0; File file = new File("FemaleCoursesElec.csv"); Scanner inputFile = new Scanner(file); while(inputFile.hasNext()) { inputFile.nextLine(); row++; } inputFile.close(); return row; } } 

主程序在這里:

 package shakeelprojectmain; import java.io.*; import java.util.*; /** * * @author lenovo */ public class ShakeelProjectMain { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { ArrayOfCourses array11 = new ArrayOfCourses(); String[][] array1 = array11.getAllCourses(); System.out.println(array1[0][0]+"\\n" + array1[0][2]); } } 

但是每次運行此命令時,StringTekonizer似乎都出現了故障?

錯誤顯示了這一點

Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at shakeelprojectmain.ArrayOfCourses.getAllCourses(ArrayOfCourses.java:40)
at shakeelprojectmain.ShakeelProjectMain.main(ShakeelProjectMain.java:25)

我嘗試了很多次來解決這個問題,但是我不能,應該如何解決呢?

這里:

        while(token.hasMoreTokens()) {

保證至少有一個令牌。 但在這兒:

            for (int j = 0 ; j < getCol() ; j++) {
                array1[i][j] = token.nextToken();

您遍歷不止一個。 每個hasMoreTokens()只能調用一次nextToken() hasMoreTokens()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM