【发布时间】:2015-01-30 18:38:22
【问题描述】:
这个程序差不多完成了,但是当它被整理出来时,权重是按照从小到大的顺序排列的,这是正确的。唯一的问题是与体重相关的姓名和年龄没有按体重排序。
例如
迈克 25 180 仁 36 105 山姆 22 120
我应该得到
仁 36 105 山姆 22 120 迈克 25 180
但我明白了
迈克 25 105 仁 36 120 山姆 22 180
import java.util.*;
import java.util.ArrayList;
import java.util.List;
public class Lab0 {
public static void main(String[] args) {
//Scanner and variables
Scanner keyboard = new Scanner (System.in);
String name = "";
int age;
double weight;
int number;
//Creates list for name, age, and weight
ArrayList<String> Name = new ArrayList<String>();
ArrayList<Integer> Age = new ArrayList<Integer>();
ArrayList<Double> Weight = new ArrayList<Double>();
System.out.println("Enter the information needed.");
//Ask user to enter information needed
while (true){
System.out.print("Enter last name: ");
name = keyboard.nextLine();
if(name.equalsIgnoreCase("FINISHED")){
break;
}
else {
Name.add(name);
System.out.print("Enter age: ");
age = keyboard.nextInt();
Age.add(age);
System.out.print("Enter weight: ");
weight = keyboard.nextDouble();
Weight.add(weight);
keyboard.nextLine();
System.out.println("==========================================\n");
}
}
//new list to sort weight and age and name
ArrayList<String> NameList = Name;
ArrayList<Integer> AgeList = Age;
ArrayList<Double> WeightList = Weight;
Collections.sort(Weight);
for(int i=0; i<Weight.size(); i++){
for (int j=0; j<Weight.size(); j++){
if(WeightList.get(j) == Weight.get(i)){
Name.set(j, NameList.get(i));
Age.set(j, AgeList.get(i));
}
else;
}
}
//prints out information entered
for (int k=0; k<Weight.size(); k++){
System.out.println("Name: " + Name.get(k) + " Age: " + Age.get(k)
+ " weight: " + Weight.get(k));
}
while (true){
System.out.println("=============================================");
System.out.print("Enter a last name that you listed: ");
String Search = keyboard.next();
int index = Name.indexOf(Search);
if (index >=0){
System.out.println("Age: " + Age.get(index));
System.out.println("Weight: " + Weight.get(index));
}
else if(Search.equalsIgnoreCase ("DONE")){
System.exit(0);
}
else{
System.out.println("NOT FOUND");
}
}
}
}
【问题讨论】:
-
为什么不创建一个 Person 对象并创建一个 Comparable 方法?
-
您应该准确地说明作业是什么。就个人而言,我会创建一个“Person”对象列表并对其进行排序,而不是使用三个单独的列表,但这可能不是您的任务,所以请告诉我们。
-
我们必须使用一个数组进行赋值来列出提供的信息。
-
你可能想和你的教授谈谈,问一些澄清问题。一个合理的解决方案是创建一个封装 Person 的类(如 @ChrisForrence 和 @RealSkeptic 所建议的那样)。该解决方案仍将使用一个数组,只有一个数组而不是三个。
-
您可能想访问this资源;它很好地解释了对象的排序。
标签: java arrays collections