如何按字母顺序打印第二个单词?|JAVA



我必须请求用户输入(输入字数没有任何限制(,然后程序必须按字母顺序打印第二个单词。

说明

编写一个程序,输入用户的单词,直到用户进入"退出"。当用户输入"退出"时,程序应按字母顺序显示第二个单词。您的程序不应区分大小写。

"您应该在解决方案中只使用while循环">

使用Scanner#nextLine()捕获许多空格分隔的字符,然后使用String#split(String)方法将输入拆分为单词数组。

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scanner.nextLine();
String[] words = sentence.split("\s");

由于单词需要排序(问题要求">按字母顺序出现的第二个单词",我们可以使用各种方法。一种简单的方法是使用Java Streams API。

words = Stream.of(words).sorted().toArray(String[]::new);

然而,对于这个特定的分配,OP指出必须专门使用while循环。因此,仅使用while循环:

int i = 0;
while (i < words.length - 1) {
// Checking the condition for two
// adjacent words of the array
if (words[i].compareTo(words[i + 1]) > 0) {
// Swapping the elements if the next word
// precedes the current alphabetically
String temp = words[i];
words[i] = words[i + 1];
words[i + 1] = temp;
// we must keep resetting the index back to zero
// when a sort occurs
i = -1;
}
i++;
}

这显然不是最优化的循环,但出于学术目的,它足够清晰易懂。以下面的句子为例(为了简单起见,使用所有小写字母(:

the quick brown fox jumps over the lazy dog

按字母顺序排序应产生

[ brown, dog, fox, jumps, lazy, over, quick, the, the ]

回顾前几次迭代:

  1. 在第一次迭代中,单词";以及";快速";交换,索引i重置回零
  2. 在第二次迭代中(i再次等于零(;快速";以及";";相对于彼此的顺序是正确的。它们不会交换,并且索引会增加一
  3. 在第三次迭代中(i等于1(;";以及";棕色";被交换,并且索引被重置回零
  4. 在第四次迭代中(i再次等于零(;快速";以及";棕色";被排序,并且索引被重置回零

在4次迭代后,数组被部分排序:

[ brown, quick, the, fox, jumps, over, the, lazy, dog ]

该过程继续进行,直到在它们的前一个邻居"之前的所有单词都被删除为止;冒泡";到表面。最终,所有单词都将被排序,索引将等于单词计数,并且该过程将停止。对于我提供的句子,排序需要90次迭代才能完成。此值与数组的大小无关。迭代次数取决于其他因素以及

综合来看,解决方案如下:

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scanner.nextLine();
String[] words = sentence.toLowerCase().split("\s");
if (words.length < 2) {
System.err.println("Not enough words were entered");
System.exit(-1);
}
int i = 0;
while (i < words.length - 1) {
if (words[i].compareTo(words[i + 1]) > 0) {
String temp = words[i];
words[i] = words[i + 1];
words[i + 1] = temp;
i = -1;
}
i++;
}
System.out.println("The second word is: " + words[1]);
}

对于我在这个例子中使用的句子,输出打印出

dog

基于此新信息:

编写一个程序,输入用户的单词,直到用户进入"退出"。当用户输入"退出"时,程序应按字母顺序显示第二个单词。您的程序不应区分大小写

解决方案将在循环中提示用户(使用while循环作为给定约束(。

String input = "";
Scanner scanner = new Scanner(System.in);
List<String> words = new ArrayList<>();
boolean isExit = false;
System.out.println("For this problem, you must enter at least two words.");
while (!isExit) {
System.out.print("Enter a word (type "exit" to finish): ");
input = scanner.next();
isExit = "exit".equalsIgnoreCase(input);
if (!isExit) {
words.add(input.toLowerCase());
}
}
scanner.close();

上面的代码片段做了一些必要的事情:

  1. 使用ArrayList而不是数组来允许集合的无限增长"调整大小"数组是一个比使用这个Java专用类成本高得多的过程
  2. 检查输入的单词是否为";退出";这是终止循环的特殊情况输入。它不是,也不应该是要评估的单词的一部分

循环操作结束后,其余代码应该基本相同。我们必须评估单词集,并检查哪个单词是按字母顺序排列的第二个单词。为此,我们所需要做的就是对集合进行排序,并返回索引1处的单词。由于我已经提供了对数组进行排序的循环解决方案,因此我将展示对集合进行排序的更好方法。当然,最简单的方法是调用Collections#sort()

if (words.size() < 2) {
System.err.println("Not enough words were entered");
System.exit(-1);
}
Collections.sort(words);
System.out.println("Second word in alphabetical order: " + words.get(1));

Collections#sort()需要注意的是,该操作会修改给定的列表。这可能是可取的,也可能不是可取的。在某些情况下,可能必须保留原始列表。对于这些情况,我们可以使用StreamsAPI的另一种Java标准库方法:

List<String> sortedWords = words.stream().sorted().collect(Collectors.toList());
System.out.println("Second word in alphabetical order: " + sortedWords.get(1));

使用我在以前版本中使用的相同单词,结果与预期的相同

Enter a word (type "exit" to finish): the
Enter a word (type "exit" to finish): quick
Enter a word (type "exit" to finish): brown
Enter a word (type "exit" to finish): fox
Enter a word (type "exit" to finish): jumps
Enter a word (type "exit" to finish): over
Enter a word (type "exit" to finish): the
Enter a word (type "exit" to finish): lazy
Enter a word (type "exit" to finish): dog
Enter a word (type "exit" to finish): exit
Second word in alphabetical order: dog

最新更新