[英]Sort arraylist by double and String
我们被赋予了一项任务:
我能够创建一个代码但是在第一次打印时没有显示正确的结果。 我必须再次尝试进行实际排序。
我对编程很新,这让我很困惑。 有任何想法吗? 谢谢!
private void listDogs() {
boolean length = false;
for (int i = 0; i < dogs.size(); i++) {
length = true;
}
if (dogs.isEmpty()) {
System.out.println("Error: no dogs in register");
}else {
System.out.println("Please enter the tail lenght minimum: ");
double tailLength = scan.nextDouble();
scan.nextLine();
Collections.sort(dogs);
for (int i = 0; i < dogs.size(); i++) {
if (dogs.get(i).getTailLength() >= tailLength) {
System.out.println(dogs.get(i));
length = true;
}
}
if (length == false) {
System.out.println("Error: No dog is registered with this tail length.");
}
@Override
public int compareTo(Dog o) {
// TODO Auto-generated method stub
int compare = Double.compare(tailLength, o.tailLength);
if (compare == 0) {
compare = Double.compare(tailLength, o.tailLength);
}
if (compare == 0) {
compare = name.compareTo(o.name);
}
return compare;
}
我不确定这是否能解决你的问题,但你有一个问题
scan.nextLine();
在你的代码中,我不明白是否必须存在,因为据我所知它只等待你输入一些东西,然后它甚至不会将它保存在一个变量中。 所以你可能会删除这一行(第12行)。
你试试这个吗?
import java.util.ArrayList;
import java.util.Collections;
public class Dog implements Comparable<Dog> {
private double tailLength;
private String name;
public Dog(final double _tailLength, final String _name) {
tailLength = _tailLength;
name = _name;
}
@Override
public String toString() {
return "Dog [tailLength=" + tailLength + ", name=" + name + "]";
}
@Override
public int compareTo(final Dog o) {
int res = Double.compare(tailLength, o.getTailLength());
if (res == 0) {
res = name.compareTo(o.getName());
}
return res;
}
public double getTailLength() {
return tailLength;
}
public void setTailLength(final double tailLength) {
this.tailLength = tailLength;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public static void main(final String[] args) {
final ArrayList<Dog> dogs = new ArrayList<Dog>();
dogs.add(new Dog(2, "Dog D"));
dogs.add(new Dog(2, "Dog A"));
dogs.add(new Dog(5, "Dog C"));
dogs.add(new Dog(4, "Dog A"));
dogs.add(new Dog(3, "Dog A"));
dogs.add(new Dog(3, "Dog B"));
dogs.add(new Dog(1, "Dog A"));
// Sort Dog by tailLength and name
Collections.sort(dogs);
final Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("tailLength: ");
final double inputTaillength = sc.nextDouble();
for (final Dog dog : dogs) {
if (dog.tailLength == inputTaillength) {
System.out.println(dog);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.