【问题标题】:Set a variable value in one class, which is returned by a method in another在一个类中设置一个变量值,该值由另一个类中的方法返回
【发布时间】:2016-04-08 16:38:27
【问题描述】:

所以我有 2 节课。第一个从文件中读取信息并将其存储在二维数组中,然后返回。像这样:

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。必须定义显式构造函数

我什至不知道我是否应该这样做,所以感谢任何帮助!

【问题讨论】:

  • 你能发布一个堆栈跟踪或其他东西吗,因为它对我有用。
  • 好的,你的第二个类中的方法也需要抛出一个 IOException 否则你会得到这个错误。您可能不应该使用 throw 方法,而是使用 try-catch。

标签: java multidimensional-array return


【解决方案1】:

为什么不捕获 IOException 而不是将其扔到类“Skaitymas”构造函数中

try{
        while (reader.readLine() != null){
            lines++;
        }
        reader.close();
    }catch (FileNotFoundException e) {
        e.printStackTrace();    
    }catch(IOException e)
{
e.printStackTrace();
}

【讨论】:

  • 是的 ^ 正是我在评论中所说的
猜你喜欢
  • 2019-01-12
  • 1970-01-01
  • 2023-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多