gpt4 book ai didi

java - 将文件加载到二维数组时出现 CSV 错误

转载 作者:行者123 更新时间:2023-12-01 08:46:02 24 4
gpt4 key购买 nike

我有一个 CSV 文件,我的任务包括获取该文件并将其加载到二维数组中。我已经计算了有多少行以及有多少列,但是当我将其加载到数组中时,我收到错误

"non-static variable filetable cannot be referenced from a static context"

但是如果我这样做public static String[][] filetable = new String[rows][cols];

我收到错误

Illegal reference forward Usage of static non-final variable during intialization

代码:

public String[][] filetable = new String[rows][cols];//The second error doesn't show up here since I haven't put 'static' after public.
public static int rows = 0;
public static int cols = 0;

public static void to_Array(File example)
{


try
{
FileReader file = new FileReader(example);
Scanner sc = new Scanner(file);

if(sc.hasNextLine())
{
String[] tokens = sc.nextLine().split(",");
cols = tokens.length;
rows++;
}

while(sc.hasNextLine())
{
rows++;
sc.nextLine();
}

//Probably not the right way to load the file into the array, but will fix it later
for(int r = 0; r < rows; r++)
{
for(int c = 0; c < cols; c++)
{
filetable[r][c] = sc.next();// This where the first error shows up
}
}


}
catch (FileNotFoundException e)
{
System.out.println(e);
}

最佳答案

public static void  method 

如果方法是静态的,则仅当局部变量也是静态的时才可以引用它们

public SomeClass {
private static String var1;
private String var2;

public void someMethod(){
this.var2 // is allowed
this.var1 // is allowed
}

public static void someMethod(){
this.var2 // is allowed
this.var1 // is not allowed
}



}

我建议您在类中创建一个方法,而不是在 main() 方法中创建该类的新实例,然后调用该方法

 SomeClass test = new SomeClass():
test.someMethod()// copy the code of the main to this method

关于java - 将文件加载到二维数组时出现 CSV 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43032269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com