Java 将项目均匀分布在任意数量的类别上
我想写一个将数据分配到“年龄”类别的主要方法。 每个数据项都有不同的名称和年龄。年龄分类跨越5岁,因此0-5岁、5-10岁、10-15岁等。 我只想要其中显示项目的类别 因此,如果输入是: 理查德,15岁 海伦,24岁 史蒂文,16岁 埃德温,19岁 弗雷德里克,12岁 输出类似于: 计算类别: 0-5,5-10,10-15,15-20,20-25 分布: 10-15:弗雷德里克 15-20:理查德、史蒂文、埃德温 20-25:HelenJava 将项目均匀分布在任意数量的类别上,java,main,Java,Main,我想写一个将数据分配到“年龄”类别的主要方法。 每个数据项都有不同的名称和年龄。年龄分类跨越5岁,因此0-5岁、5-10岁、10-15岁等。 我只想要其中显示项目的类别 因此,如果输入是: 理查德,15岁 海伦,24岁 史蒂文,16岁 埃德温,19岁 弗雷德里克,12岁 输出类似于: 计算类别: 0-5,5-10,10-15,15-20,20-25 分布: 10-15:弗雷德里克 15-20:理查德、史蒂文、埃德温 20-25:Helen公共静态void main(字符串[]args)引发IOE
公共静态void main(字符串[]args)引发IOException{
public static void main(String[] args) throws IOException {
Map<Integer, List<String>> result = new HashMap<Integer, List<String>>();
while (true) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
if (!line.contains(",")) {
System.out.println("incorrect input string");
continue;
}
String name = line.split(",")[0];
String age = line.split(",")[1];
age = age.trim();
int ageInt = -1;
try {
ageInt = Integer.parseInt(age);
} catch (NumberFormatException e) {
System.out.println("age not a number");
continue;
}
ageInt = ageInt - ageInt % 5;
List<String> names = result.get(ageInt);
if (names == null) {
names = new ArrayList<String>();
}
names.add(name);
result.put(ageInt, names);
printResult(result);
}
}
private static void printResult(Map<Integer, List<String>> result) {
List<Integer> ages = new ArrayList<Integer>();
ages.addAll(result.keySet());
Collections.sort(ages);
for (Integer integer : ages) {
List<String> name2 = result.get(integer);
System.out.println(integer + " - " + (integer + 5) + " : ");
for (String s : name2) {
System.out.println(" " + s);
}
}
}
映射结果=新的HashMap();
while(true){
BufferedReader br=新的BufferedReader(新的InputStreamReader(System.in));
String line=br.readLine();
如果(!line.contains(“,”){
System.out.println(“不正确的输入字符串”);
继续;
}
字符串名称=行。拆分(“,”[0];
字符串年龄=行分割(“,”[1];
age=age.trim();
int-ageInt=-1;
试一试{
ageInt=Integer.parseInt(年龄);
}捕获(数字格式){
System.out.println(“年龄不是数字”);
继续;
}
ageInt=ageInt-ageInt%5;
列表名称=result.get(ageInt);
如果(名称==null){
名称=新的ArrayList();
}
名称。添加(名称);
结果.put(ageInt,name);
打印结果(result);
}
}
私有静态void打印结果(映射结果){
列表年龄=新建ArrayList();
ages.addAll(result.keySet());
收集。分类(年龄);
用于(整数:年龄){
列表名称2=result.get(整数);
System.out.println(整数+“-”+(整数+5)+“:”);
for(字符串s:name2){
系统输出打印项次(“+s”);
}
}
}
问题是什么/你试过什么?HashMap
是你的朋友。你至少应该发布你尝试过的代码,并指定你的问题所在。至少尝试一下,伙计……问题在哪里?