感觉就像我离得这么近,只是不知道该把什么放在“如果状态”和事情的顺序上。请帮帮忙。也不确定用交换方法做什么好吗?
private static void selectionSort(String[] words, int numWords)
{
for (int i = 0; i < words.length; i++)
{
int min = i;
for(int j = i+1; j < words.length; j++)
{
if(words[index]<words[minIndex])
{
min = j;
}
swap(words, i, j);
}
}
}
public static int indexOfNextSmallest(String[] words, int startIndex)
{
int minIndex = startIndex;
for(int i = startIndex; i < words.length; i++) {
if(words[i].compareTo(words[minIndex]) < 0)
minIndex = i;
}
return minIndex;
}
private static void swap(String[] words, int i, int j)
{
String swap = words[i];
words[i] = words[j];
words[j] = swap;
}试图添加用户验证。想知道我是应该用下面的方法来做,还是在主方法上做呢?
private static int getMenuChoice(Scanner stdIn)
{
int option = 0;
System.out.println("\n1: Add Word");
System.out.println("2: Remove Word");
System.out.println("3: Print Words");
System.out.println("4: Quit");
System.out.print("Choose an option(1-4): ");
option = stdIn.nextInt();
return option;
}发布于 2014-05-08 20:04:18
您正在尝试使用'<'运算符比较两个字符串,但该操作符不工作。相反,您应该使用compareTo函数来比较两个可比较的对象。
if(words[index]<words[minIndex]) // doesnt work - Compilation error
{
min = j;
}在方法selectionSort中更改if条件如下:
if(words[j].comapareTo(words[min]) < 0)
{
min = j;
}此外,您还需要在索引i& min处交换单词,而不是交换i&j。
swap(words, i, j); //wrong
swap(words, i, min); //correct - as it swaps min word & current wordhttps://stackoverflow.com/questions/23551369
复制相似问题