我是Java编程新手。我正在准备一项作业,我需要一些关于我的代码的帮助。说明说我需要在我的numberOfRows()
和convertFileArray()
方法中处理异常。练习包括读取 csv 文件、将文件转换为多维数组、在屏幕上打印数组。我的程序运行良好,我唯一的问题是我无法弄清楚我可以在这两种方法中处理哪些异常。
我写了一般例外只是因为我不知道该怎么做。任何建议都会非常有帮助。此外,我只发布需要放置 try-catch 块的课程。提前致谢。
这是我的代码:
import java.io.*;
import java.nio.file.*;
import java.util.StringTokenizer;
public class ReadFiles {
int rows = 0;
int columns = 0;
String s = null;
private String[][] arrayValues;
Path filePath;
public ReadFiles(String name) {
filePath = Paths.get("C:\\stocks\\" + name); //newMSFT.csv
System.out.println("Path for file entered " + filePath.toString());
}
public boolean fileExists() {
if(Files.exists(filePath))
return true;
else
return false;
}
public int numberOfRows() {
try {
InputStream data = new BufferedInputStream(
Files.newInputStream(filePath));
BufferedReader reader = new BufferedReader(
new InputStreamReader(data));
s = reader.readLine();
while(s != null) {
rows++;
s = reader.readLine();
}
}
catch(Exception e) {
System.out.println("Message: " + e);
}
return rows;
}
public void convertFileArray() {
try {
InputStream data = new BufferedInputStream(
Files.newInputStream(filePath));
BufferedReader reader = new BufferedReader(
new InputStreamReader(data));
s = reader.readLine();
StringTokenizer z = new StringTokenizer(s, ",");
columns = z.countTokens();
arrayValues = new String[rows][columns];
for(int x = 0; x < rows; x++) {
z = new StringTokenizer(s, ",");
//when there are still more tokens, place it in the array:
int y = 0;
while(z.hasMoreTokens()) {
arrayValues[x][y] = z.nextToken();
y++;
}
s = reader.readLine();
}
System.out.println("An array was created and has " +
rows + " rows and " + columns + " columns.");
}
catch(Exception e) {
System.out.println("Message: " + e);
e.printStackTrace();
}
}
public void printArray() {
System.out.println("The data from the array is >> ");
for(int a = 0; a < rows; a++) {
String output = null;
for(int b = 0; b < columns; b++) {
System.out.print(arrayValues[a][b] + " ");
}
System.out.println();
}
}
public String[][] getArrayValues() {
return arrayValues;
}
}