在Java中如何将数据从文件读入数组?
我需要一些帮助将文本文件中的数据读取到ArrayList中。第一部分创建ArrayList并将其放入文本文件中,效果非常好。我只需要在标记区域的末尾得到一些帮助 请注意,有些标识符使用我的母语在Java中如何将数据从文件读入数组?,java,file-io,arraylist,Java,File Io,Arraylist,我需要一些帮助将文本文件中的数据读取到ArrayList中。第一部分创建ArrayList并将其放入文本文件中,效果非常好。我只需要在标记区域的末尾得到一些帮助 请注意,有些标识符使用我的母语 public class ContAngajat { String username; String password; } public class CreazaCont { // creating the arraylist and putting it into a file
public class ContAngajat {
String username;
String password;
}
public class CreazaCont {
// creating the arraylist and putting it into a file
public static void ang(String args[]) {
ArrayList<ContAngajat> angajati=new ArrayList<ContAngajat>(50);
Scanner diskScanner = new Scanner(in);
Scanner forn = new Scanner(in);
int n;
out.print("Introduceti numarul de conturi noi care doriti sa le introduceti: ");
n=forn.nextInt();
out.println();
try{
FileWriter fw = new FileWriter("ConturiAngajati.txt", true);
for(int i=0; i<n; i++){
ContAngajat cont = new ContAngajat();
out.print("Username: ");
cont.username=diskScanner.nextLine();
out.print("Password: ");
cont.password=diskScanner.nextLine();
angajati.add(cont);
fw.write(cont.username + " ");
fw.write(cont.password +"|");
}
fw.close();
}
catch(IOException ex){
System.out.println("Could not write to file");
System.exit(0);
}
for (int i=0; i<n; i++) {
out.println("username: " + angajati.get(i).username + " password: " +angajati.get(i).password );
}
}
// HERE I'M TRING TO GET THE ARRAYLIST OUT OF THE FILE
public static void RdAng(String args[]) {
ArrayList<ContAngajat> angajati=new ArrayList<ContAngajat>(50);
ContAngajat cont = new ContAngajat();
int count,i2,i;
try{
FileReader fr = new FileReader("ConturiAngajati.txt");
BufferedReader br = new BufferedReader(fr);
String line = "";
while((line=br.readLine())!=null) {
String[] theline=line.split("|");
count=theline.length;
for(i=0;i<theline.length;i++) {
String[] theword = theline[i].split(" ");
}
}
for(i2=0;i2<count;i2++) {
ContAngajat contrd = new ContAngajat();
// "ERROR" OVER HERE
for (int ird=0; ird <theword.length; ird++) {
cont.username=theword[0];
cont.password=theword[1];
// they keep telling me "theword cannot be resolved" whenever i try to run this
}
angajati.add(contrd);
}
}
catch(IOException ex){
System.out.println("Could not read to file");
System.exit(0);
}
}
}
编译错误是无法解析单词
他们一直告诉我,无论我什么时候尝试运行,这个词都无法解决
这意味着该词未在范围中声明。您不能访问它来调用任何方法。他们说得对。您需要在更大的范围内声明该词,或者将依赖该词的代码移动到声明该词的范围内。可能您已经在if或while块中声明了它,并且您试图在声明它的块之外使用它。那是行不通的
每当您清理代码时,可能会给出更详细的答案,以便更好地阅读。您的代码在美学上看起来非常糟糕。尝试使用大多数IDE附带的代码格式化程序对其进行格式化。读起来很痛苦。是的,你必须清理这个代码。。。这段代码太难读了,太糟糕了。我认为,在编写程序之前学习如何组织代码是我能推荐的最好的方法。程序需要被组织成不同的方法、组件等。通常也有好的方法和坏的方法。这段代码有很多不好的方法。有些不是你的错。大学在教授java方面很糟糕。其他的只是早期版本的语言和旧书的问题。试着学习如何构造你们的代码。所以我临时声明了这个词,它成功了。所以这不再是问题了…:现在它说:cont.username处的线程异常=单词[0];谢谢你的礼物!不客气。如果你遇到新问题,只要问一个新问题。不要忘记正确地格式化代码,例如,Eclipse将使用Ctrl+Shift+F,并包含异常的整个堆栈跟踪,并将代码中的行指向导致异常的位置。