Это хорошая школа упражнение :-)
Предположим, что ваш входной файл в C: \ Temp \ cities.txt содержит:
London,83000000,UK
Paris,22000000,France
Madrid,32000000,Spain
Следующий класс Test.java:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class Test {
private static ArrayList<City> loadDataFromFile() throws IOException {
ArrayList<City> list = new ArrayList<City>();
BufferedReader br = null;
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\temp\\cities.txt"));
while ((sCurrentLine = br.readLine()) != null) {
String[] splittedLine = sCurrentLine.split(",");
City city = new City(splittedLine[0], Integer.parseInt(splittedLine[1]), splittedLine[2]);
list.add(city);
}
br.close();
return list;
}
public static void main(String[] args) throws IOException {
ArrayList<City> list = loadDataFromFile();
int input = Integer.parseInt(args[0]);
Iterator<City> it = list.iterator();
while (it.hasNext()) {
City currentCity = it.next();
if (currentCity.getPopulation() > input) {
System.out.println("Cities with population greater than " + input + " : " + currentCity.getName() + "," + currentCity.getCountry());
} else if (currentCity.getPopulation() == input) {
System.out.println("City with population equals to " + input + " : " + currentCity.getName() + "," + currentCity.getCountry());
} else {
System.out.println("Cities with population lower than " + input + " : " + currentCity.getName() + "," + currentCity.getCountry());
}
}
}
}
и простой POJO:
public class City {
private String name;
private int population;
private String country;
public City(String name, int population, String country) {
this.name = name;
this.population = population;
this.country = country;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Даст вам:
java Test 3200000
Cities with population greater than 32000000 : London,UK
Cities with population lower than 32000000 : Paris,France
City with population equals to 32000000 : Madrid,Spain
Создать основной метод, а затем создать 'Scanner' /' объект BufferedReader', чтобы прочитать файл, а затем разделить его на ''. Сохраните их в своем «ArrayList» и в последнем цикле через arraylist и распечатайте их :) – Parth