java - Java .csv 打印语句问题
问题描述
目前正在处理一个导入 .csv 文件(21 行,20 列)的项目,将其捕获到一个数组中,然后在电子表格中打印一个特定的单元格......目前遇到一个导致输出为 20 的问题行和一列,“null”除了输出中的第二行似乎是文件中的最后一行,第二列单元格。Null 发生了什么,为什么它会提取最后一行数据?谢谢,伙计们/姑娘们的任何意见。
public class cvsPull {
public String[][] myArray;
String csvFile = "Crime.csv";
public Class csvPull() {
myArray = new String[20][20];
try {
s = new Scanner (new BufferedReader(new FileReader(csvFile)));
while (s.hasNext()) {
int theRow = 1;
int theCol = 0;
InputLine = s.nextLine();
String[] InArray = InputLine.split(",");
for (String InArray1 : InArray) {
myArray[theRow][theCol] = InArray1;
theCol++;
if (theCol==20) {
theCol=0;
theRow++;
}
// System.out.println(myArray[theRow][theCol]);
}
}
for (String[] theString : myArray) {
System.out.println(theString[1]);
}
} catch (IOException ioe) {
System.out.println("incorrect file name" + ioe.getMessage());
}
}
解决方案
您在每个循环开始时将行计数器重置为 1:
while (s.hasNext()) {
int theRow = 1;
int theCol = 0;
这意味着文件的每一行都被写入内存中的同一位置。此外,行的第一个索引是 0 就像列一样,因此您最初需要将其设置为 0:
int theRow = 0;
while (s.hasNext()) {
int theCol = 0;
推荐阅读
- python - 读取 CSV 文件时如何使熊猫在 int64 列中使用空值
- c# - 实体框架核心:没有外键的一对多?
- c# - 是什么让 Nullable 类型可以赋值为 null?
- swift - 在 UILongPressGestureRecognizer 中,当开始状态仍为 ON 时,添加的视图不会显示
- r - R Shiny Apps - 如何停止可以从 eval 表达式中删除 OS 文件的 shell 命令
- rust - 如何在结构上与 Rust 中的私有字段匹配?
- bash - Bash:如何根据输入参数调用函数?
- angular - 在 ckeditor 的工具栏上显示提及按钮
- python - 如何不向无效路由路径添加前缀
- javascript - MySQL 会在事务回滚时自动释放连接吗?