【发布时间】:2015-05-28 22:46:28
【问题描述】:
我正在为班级做作业,我必须打开一个文本文件并将该文件转换为二维数组,以便以后可以根据用户的请求访问它。
到目前为止,我的代码是这样的:
public static void main(String[] args) throws FileNotFoundException {
//create a scanner with the file as input
Scanner in = new Scanner(new File("src/EnglishResults06-12Citywide.csv"));
//check to see if there's a line available in the file
while(in.hasNextLine()){
//get the next line
String line = in.nextLine();
}
//close scanner
in.close();
//turns file into multi-dimensional array
String[][] grades = new String[98][15];
for (int i=0; i<results.length; i++) { //loop through each row
for (int j=0; j<results[i].length; j++) { //loop through all columns within the current row
results[i][j] = request //not sure how to assign the imported csv to the variable request
}
}
System.out.printf("Grade", "Year" , "Demographic" , "Number Tested" , "Mean Scale Score" , "Num Level 1" , "Pct Level 1" , "Num Level 2" , "Pct Level 2" , "Num Level 3" , "Pct Level 3" , "Num Level 4" , "Pct Level 4" , "Num Level 3 and 4" , "Pct Level 3 and 4");
我已经导入了以下内容:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
我的文本文件有 98 行和 15 列。 这是文件:http://txt.do/xjar
我希望有人可以提供帮助。非常感谢你!!!
【问题讨论】:
-
String.split是你的朋友,使用它。您所指的文件格式称为 CSV(逗号分隔值),请考虑将其添加为标签。 -
感谢您的回复!!我究竟会在哪里使用 String.split?
-
@MichaelLaffargue 注意,split 的参数是
RegEx模式,所以用 分割。 将被 任何字符 分割,如果你不确定,您可以使用Pattern.quote(...)转义参数 -
在线上,使用正则表达式拆分,您将收到一个数组 => 示例:“我要拆分的行”.split("\\s") --> ["my ","line","to","split"]。 docs.oracle.com/javase/tutorial/essential/regex/…
-
你的评论没有错,我只是想我应该提一下,当用特殊字符分割时这可能会失败......
标签: java csv multidimensional-array 2d