我有2个域类
class Country {
String name;
List<State> statelist;
public addState(String statename) {
statelist.add(statename);
}
//getters and setters etc
}
class State implements Comparable {
String name;
// better setter compareTO etc
}
然后
public class Main {
}
输入:
4
India|TamilNadu
USA|Texas
USA|Alaska
India|Punjab
输出应该是按字母顺序排列的国家/地区,每个国家/地区都列在其下,同样按字母顺序排列。
India
Punjab
TamilNadu
USA
Alaska
Texas
我是java的新手。不确定如何阅读并将值分配给Country类。任何建议
答案 0 :(得分:0)
您无法将n
添加到由州组成的String
。您必须创建ArrayList
的实例,为其指定字符串,然后将State
添加到State
statelist
答案 1 :(得分:0)
首先,wdc在他的回答中给出的建议绝对正确。你必须做出改变。您还应该为Country类添加一个参数化构造函数,该构造函数接受一个String并将该名称存储为该字符串。
检查Scanner类以了解如何读取Stdin的读取。方法如下:
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Set<Country> country_set = new HashSet<>();
int n = sc.nextInt();
for(int i=0; i<n; i++){
String input = sc.next();
String[] pair = input.split("|");
if(country_set.contains(pair[0]){
country_set.get(pair[0]).addState(pair[1]));
}
else{
Country temp = new Country(pair[0]);
temp.addState(pair[1]);
country_set.add(temp);
}
}
}
答案 2 :(得分:0)
正如您最终将String比较,您不需要实现Comparable。请尝试以下代码:
package stackOverflow;
public class State extends Country {
String stateName;
String countryName;
public State(String stateName,String countryName) {
super(countryName,stateName);
this.stateName = stateName;
this.countryName = countryName;
}
}
,另一个类是:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class Country
{
public static HashMap<String, String> countryMap = new HashMap<String, String>();
public static ArrayList<String> countries = new ArrayList<String>();
public Country(String cntryName, String stateName ) {
if(countryMap.get(cntryName)!= null) {
countryMap.put(cntryName,countryMap.get(cntryName)+","+stateName);
}else {
countryMap.put(cntryName,stateName);
}
if(!countries.contains(cntryName))
countries.add(cntryName);
}
public static void main(String[] args) {
ArrayList<State> states = new ArrayList<State>();
states.add(new State("TamilNadu","India"));
states.add(new State("Texas","USA"));
states.add(new State("Punjab","India"));
states.add(new State("Alaska","USA"));
Collections.sort(countries);
//or Collections.sort(countries, (p,p1)->(p.compareTo(p1)));
for(String country : countries) {
System.out.println("country is :"+country+" and the states are :"+countryMap.get(country));
}
}
}