대신 scanner.next()
을하는 한 단어를해야합니다 사전에
public void openFile(){
try{
x = new Scanner(new File("D://practice.txt"));
}catch (Exception e){
System.out.println("File could not be found");
}
}
public void readFile(){
while (x.hasNextLine()){
x.nextLine();
if (x.hasNext()){
listL.add(x.next());
} else {
listL.add("");
}
if (x.hasNext()){
listR.add(x.next());
} else {
listR.add("");
}
}
}
덕분에 ... 노트 = 1.hobby와 이름을 공백으로 구분 내 현재 코드입니다 당신이 그런 짓을 할 수 있습니다 :
이와
Scanner scan = new Scanner(new File("D://practice.txt"));
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> hobbies = new ArrayList<String>();
while(scan.hasNext()){
String curLine = scan.nextLine();
int indexOfHobby = curLine.indexOf(' ');
names.add(curLine.substring(0, indexOfHobby).trim());
hobbies.add(curLine.substring(indexOfHobby).trim());
}
하나의 문제는 두 ArrayList
의 사이에 관계가 없다는 것입니다, 그래서 당신은 당신 마음을해야 할 r 인덱스를 반복합니다. 이 문제를 해결할 수있는 한 가지 방법은 name
및 hobby
을 Person
의 특성으로 가질 수 있도록 Person
클래스를 추가 한 다음 ArrayList
이 Person
입니다. 즉 다음과 같습니다
Class Person {
String name;
String hobby;
public Person(String name, String hobby){
this.name = name;
this.hobby= hobby;
}
// more methods here
}
그런 다음 메인 클래스에서, 당신이 할 거라고 :
Scanner scan = new Scanner(new File("D://practice.txt"));
ArrayList<Person> people= new ArrayList<Person>();
while(scan.hasNext()){
String curLine = scan.nextLine();
int indexOfHobby = curLine.indexOf(' ');
people.add(new Person(curLine.substring(0, indexOfHobby).trim(), curLine.substring(indexOfHobby).trim()));
}
첫 번째 단어에 공백이 있습니까? 이름/취미는 공백이나 태그로 구분됩니까? 더 많은 정보를주세요. – Darkhogg
'Billy bowling from friends'에서 ArrayList에 항목으로 'bowling with friends'를 추가하면 전체 줄을 읽은 다음 이름과 이름 사이에 오는 첫 번째 공백 문자를 분리 할 수 있습니다. 작업을 텍스트 파일에 저장하십시오. 이것은 하위 문자열 함수와 indexOf를 사용하여 수행 할 수 있습니다. 그러나 이름에 단어가 두 개 이상인 경우 쉼표와 같은 것을 사용하여 텍스트 파일을 변경하여 이름과 작업을 구분하십시오. –
@Darkhogg 1. 취미 및 이름은 공백으로 구분됩니다. 2. 이름은 한 단어 만 가질 수 있습니다. – user2891092