我有一些代码用于按字母顺序排列三个单词。我正在尝试删除底部的方法,只需将其添加到上面的代码中。但是,我无法找到一种可行的方法。任何指导或帮助将不胜感激,谢谢!
System.out.print("Please enter three words: ");
final String words = keyboard.nextLine();
final String[] parts = words.split(" ");
if (parts[0].equals(parts[1]) && parts[1].equals(parts[2])) {
System.out.println("All three of those words are the same!");
} else {
System.out.print("In alphabetical order those are: ");
alphabetizing (parts);
final int three = 3;
for (int limit = 0; limit < three; limit++) {
System.out.print(parts[limit] + " ");
}
}
}
public static void alphabetizing (final String[] parts) {
int word;
boolean check = true;
String temp;
for (word = 0; word < parts.length - 1; word++) {
if (parts[ word ].compareToIgnoreCase(parts[word + 1]) > 0) {
temp = parts[word];
parts[word] = parts[word + 1];
parts[word + 1] = temp;
check = true;
}
}
}
}
答案 0 :(得分:0)
因为你还是想做。我没有看到任何问题,为什么它不起作用。只需将其添加到您调用方法的else语句中,它应该可以工作。
System.out.print("Please enter three words: ");
Scanner keyboard = new Scanner(System.in);
final String words = keyboard.nextLine();
final String[] parts = words.split(" ");
if (parts[0].equals(parts[1]) && parts[1].equals(parts[2])) {
System.out.println("All three of those words are the same!");
} else {
System.out.print("In alphabetical order those are: ");
//boolean check = true; you don't neeed this.
String temp = "";
for (int word = 0; word < parts.length - 1; word++) {
if (parts[word].compareToIgnoreCase(parts[word + 1]) > 0) {
temp = parts[word];
parts[word] = parts[word + 1];
parts[word + 1] = temp;
}
}
final int three = 3;
for (int limit = 0; limit < three; limit++) {
System.out.print(parts[limit] + " ");
}
}
输出:
Please enter three words: a b c
In alphabetical order those are: a b c
Please enter three words: a a a
All three of those words are the same!