Java 在一个类中设置变量值,该值由另一个类中的方法返回
所以我有两门课。第一个从文件中读取信息并将其存储在二维数组中,然后返回。像这样:Java 在一个类中设置变量值,该值由另一个类中的方法返回,java,multidimensional-array,return,Java,Multidimensional Array,Return,所以我有两门课。第一个从文件中读取信息并将其存储在二维数组中,然后返回。像这样: public class Skaitymas{ File f = new File("Events.txt"); private int lines = 0; private Scanner sc; private String[][] myArray; public void skaityti() throws IOException{ BufferedReader reader = new Buff
public class Skaitymas{
File f = new File("Events.txt");
private int lines = 0;
private Scanner sc;
private String[][] myArray;
public void skaityti() throws IOException{
BufferedReader reader = new BufferedReader(new FileReader("Events.txt"));
try{
while (reader.readLine() != null){
lines++;
}
reader.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String[][] iMasyva() throws IOException{
sc = new Scanner(new File("Events.txt"));
String linija = null;
int counter = 0;
myArray = new String[lines][5];
for(int i = 0; i<myArray.length; i++){
linija = sc.nextLine().toString();
String[] dabartinesLinijosStringai = linija.split(" ");
for(int j = 0; j<myArray[0].length; j++){
myArray[counter][j] = dabartinesLinijosStringai[j];
}
counter++;
}
return myArray; //The 2D array i wish to return
}
}
Skaitymas read = new Skaitymas();
String[][] mas = read.iMasyva();
但我得到了这个错误:默认构造函数无法处理隐式超级构造函数引发的异常类型IOException。必须定义显式构造函数
try{
while (reader.readLine() != null){
lines++;
}
reader.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e)
{
e.printStackTrace();
}
我甚至不知道我是否应该这样做,所以任何帮助都是感激的 为什么不捕获IOException而不是将其抛出到类“Skaitymas”构造函数中
try{
while (reader.readLine() != null){
lines++;
}
reader.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e)
{
e.printStackTrace();
}
你可以发布一个堆栈跟踪或其他东西,因为它对我有用。好的,你的第二个类中的方法也需要抛出一个IOException,否则你会得到这个错误。您可能不应该使用方法throw,而应该使用try-catch。是的,这正是我在评论中所说的