所以,基本上,我将有一个名为" data.txt"
的文件此文件将包含:
Name;Age;State
示例:
Anne;19;S (Single/Married/etc)
Gustav;18;S
Dinisio;19;C
基本上,我想读取文件,将信息放入数组,并显示/列出它,例如:
Name: Anne
Age: 19
State: S
Name: Gustav
Age: 18
State: S
Name: Dinisio
Age: 19
State: C
为此我创建了一个具有以下结构的类:
class Person {
String name;
int age;
char state;
}
变量:
int i, option;
String s;
File f = new File("C:\\Users\\Gustavo\\Desktop\\data.txt");
Person arrayPerson[] = new Person[4]; // It has 4 persons only
我有以下菜单:
System.out.print("Choose an option: ");
System.out.println("\n1- Load");
System.out.println("2- List");
System.out.print("Option: ");
option= ler.nextInt();
System.out.println("");
switch(option)
{
case 1:
{
Exercicio07Java.openRead(f);
while((s = Exercicio07Java.readLine()) != null)
{
String[] str = s.split(";");
arrayPerson[i] = new Person();
arrayPerson[i].name = str[0];
arrayPerson[i].age = Integer.valueOf(str[1]);
arrayPerson[i].state = str[2].charAt(0);
i++;
}
Exercicio07Java.closeRead();
break;
}
case 2:
{
for(i = 0; i < 4; i++)
{
System.out.println(arrayPerson[i].nome);
System.out.println(arrayPerson[i].idade);
System.out.println(arrayPerson[i].estado);
}
break;
}
}
我或多或少知道如何阅读信息,但我不知道如何将其传递到数组中,而它被 ;
有什么想法吗?
答案 0 :(得分:1)
所以说如果你有四行,你可以这样做:
int index = 0;
while//read line in a file {
String[] str = lineFromFile.split(";");//will split line on semicolon and you have name in index 0 of array, age in index 1 of str array and so on
//validate you have all three parameters that you need to create person object.
Person person = new Person(str[0], convertToInt(str[1]), str[2].charAt(0));//assuming you have constructor that accepts name, converted method to convert age to integer, state
arrayPerson[index++]=person;
}
答案 1 :(得分:1)
使用String.Split(String delimiter)返回String []。如果您将整行读作字符串并创建新人。见下文。这可能是一个寻找你的好地方。
for(int i = 0; i < persons.size(); i++) {
String [] info = /**Line From File Here As A String*/.split(";");
persons[i].name = info[0];
persons[i].age = info[1];
persons[i].state = info[2];
}
答案 2 :(得分:0)
你可以使用bufferedreader进行读取和分割;标记 在此之后 设置arrayproperty像 arrayPerso [i] .name = temp [0] //这里temp是为分割值存储生成的字符串数组