这里是Java初学者,请耐心等待。所以我需要导入一个如下所示的txt文件
一个
德国
印度
B
越南
中国
程序需要比较用户输入的国家/地区,然后确定它属于 A 组还是 B 组并返回该组。我被告知使用 ArrayList
。目前我的代码看起来像
public class regionCountry
{
public String region;
public ArrayList <String> countryList;
}
public class destination
{
public static void main (String [] args)
{
ArrayList<regionCountry> rc = new ArrayList<regionCountry>;
}
}
但我还是不知道该怎么办。任何帮助将不胜感激。
最佳答案
您可以按照以下步骤操作。
1. Read your file (You can use Scanner)
2. Split data and store them in a `ArrayList`.
现在让我们尝试解决这些问题。
如何读取文件?
File file=new File("yourFilePath");
Scanner scanner=new Scanner(file);
while (scanner.hasNextLine()){
// now you can get content of file from here.
}
然后分割内容并创建对象集区域的实例并添加国家/地区列表。
注意:
使用正确的命名转换。将 regionCountry
更改为 RegionCountry
。类名应以大写字母开头。
将所有变量设为私有(private)并添加公共(public) getter 和 setter。
编辑:供您发表评论。如何确定组别和国家?
File file=new File("/home/ruchira/Test.txt");
Scanner scanner=new Scanner(file);
RegionCountry regionCountry = null;
List<RegionCountry> regionCountryList=new ArrayList<>();
List<String> groupList=new ArrayList<>();
groupList.add("A");
groupList.add("B");
List<String> countryList = null;
while (scanner.hasNextLine()){
String line=scanner.nextLine();
if(!"".equals(line)){
if(groupList.contains(line.trim())){
if(regionCountry!=null&&groupList.contains(regionCountry.getRegion())){
regionCountryList.add(regionCountry);
}
regionCountry=new RegionCountry();
regionCountry.setRegion(line);
countryList=new ArrayList<>();
}else {
countryList.add(line); // those will never be null in this logic
regionCountry.setCountryList(countryList);
}
}
}
regionCountryList.add(regionCountry);// last group you have to take from here.
System.out.println(regionCountryList);
输出:(我在 RegionCountry
中重写了 toString()
)
[RegionCountry{region='A', countryList=[Germany, India]}, RegionCountry{region='B', countryList=[Vietnam, China]}]
关于java - Java中如何将一个文件导入到多个ArrayList中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25801317/