感觉好像我这么近,只是不知道该放什么"如果声明"和事物的顺序。请帮忙。还不确定如何处理swap方法呢?
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;
}
答案 0 :(得分:2)
您正尝试使用'&lt;'运算符比较2个字符串,但这些运算符不起作用。相反,您应该使用compareTo函数来比较可比较的两个对象。
if(words[index]<words[minIndex]) // doesnt work - Compilation error
{
min = j;
}
在方法selectionSort中更改if条件,如下所示:
if(words[j].comapareTo(words[min]) < 0)
{
min = j;
}
你还需要在索引i&amp;中交换单词。分钟,而不是交换i&amp; Ĵ
swap(words, i, j); //wrong
swap(words, i, min); //correct - as it swaps min word & current word