我有一个文本文件,在该文件中,我尝试使用不同的方法来分隔文件中的特定内容,并根据要打印的方法进行打印。在这种情况下,我使用不同的方法来区分人们所居住的国家(即john mexico
或william cuba
。我做了两个不同的类(主类和超级类)。
这是超类
import java.util.*;
public class myHashSet{
public static HashSet <String> Mexico = new HashSet<>();
public static HashSet <String> Cuba = new HashSet<>();
public static HashSet <String> Jamaica = new HashSet<>();
//only mexico
public void Mexico(){
Mexico.removeAll(Cuba);
Mexico.removeAll(Jamaica);
Iterator <String> m = Mexico.iterator();
while(m.hasNext()){
System.out.println(m.next());
}
}
//only cuba
public void Cuba(){
Cuba.removeAll(Mexico);
Cuba.removeAll(Jamaica);
Iterator <String> m = Cuba.iterator();
while(m.hasNext()){
System.out.println(m.next());
}
}
//only jamaica
public void Jamaica(){
Jamaica.removeAll(Mexico);
Jamaica.removeAll(Cuba);
Iterator <String> m = Jamaica.iterator();
while(m.hasNext()){
System.out.println(m.next());
}
}
//person from every country
public void orCountries(){
Jamaica.addAll(Mexico);
Jamaica.addAll(Cuba);
Iterator <String> m = Jamaica.iterator();
while(m.hasNext()){
System.out.println(m.next());
}
}
//people who have been to all countries
public void allCountries(){
Jamaica.retainAll(Mexico);
Jamaica.retainAll(Cuba);
Iterator <String> m = Jamaica.iterator();
while(m.hasNext()){
System.out.println(m.next());
}
}
//only mexico and cuba
public void MexicoandCuba(){
Mexico.addAll(Cuba);
Cuba.removeAll(Jamaica);
Iterator <String> m = Mexico.iterator();
while(m.hasNext()){
System.out.println(m.next());
}
}
}
然后这是我的主类,应该使用超类的方法:
import java.io.*;
import java.util.Scanner;
public class people extends myHashSet{
public people(String string) throws FileNotFoundException {
Scanner input = new Scanner(new File("people.txt"));
read(input);
}
public void read(Scanner input){
while(input.hasNext()){
String name = input.next();
String country = input.next();
System.out.println(name + " " + country);
}
}
public static void main(String[] args) throws FileNotFoundException {
people p = new people("people.txt");
p.Mexico();
p.Cuba();
p.Jamaica();
p.orCountries();
p.allCountries();
p.MexicoandCuba();
}
}
我知道问题在于myHashSet
中的方法未读取文件,这就是我对处理方法感到困惑的原因。任何帮助将不胜感激!