所以基本上我的代码正在做问题所说的事情。按照代码现在的布局方式,它给出了正确的结果,但是当我更改 .add 代码片段的顺序时,它每次都会给出不同的结果。我觉得 compareTo
方法很好,但是我错过了什么吗?我正在努力获得最小的结果。
提前致谢。
package lists;
import java.util.*;
public class Lab4 {
public static <T extends Comparable> int smallest(List<T> l) {
if (l.size() == 0)
return -1;
else {
Iterator<T> it = l.iterator();
T smallestSoFar = it.next();
T temp;
int smallestPos = 0;
int i = 0; //used to indicate position in list of next item
while (it.hasNext()) {
temp = it.next();
if (temp.compareTo(smallestSoFar) > 0) {
smallestSoFar = temp;
smallestPos++;
}
i++;
}
return smallestPos;
}
}
public static <T extends Comparable> void deleteSmallest(List<T> l) { // for exercise 3
}
public static void main(String[] args) {
Vector<String> vec1 = new Vector<String>();
vec1.add("Hello");
vec1.add("xxxx");
vec1.add("world");
vec1.add("aardvark");
int smallPos = smallest(vec1);
if (smallPos != -1)
System.out.println("smallest entry is " + vec1.elementAt(smallPos) + " at position " + smallPos);
Vector<Integer> vec2 = new Vector<Integer>();
vec2.add(new Integer(47));
vec2.add(new Integer(247));
vec2.add(new Integer(17));
vec2.add(new Integer(399));
smallPos = smallest(vec2);
if (smallPos != -1)
System.out.println("smallest entry is " + vec2.elementAt(smallPos) + " at position " + smallPos);
}
}
最佳答案
你的比较测试是错误的。目前您正在选择最大的值。
if (temp.compareTo(smallestSoFar) > 0) {
应该是
if (temp.compareTo(smallestSoFar) < 0) {
另外,smallestPos++;
应该是smallestPos=i;
当前您正在返回“最小”值更改的次数。
关于java - 如果添加单词/数字的顺序发生变化,我的“最小方法”会给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45390168/