【发布时间】:2016-10-28 01:34:52
【问题描述】:
我有这段代码是为了按字母顺序排列三个单词。我正在尝试删除底部的方法,并将其添加到上面的代码中。但是,我想不出一种工作方式来做到这一点。任何指导或帮助将不胜感激,谢谢!
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;
}
}
}
}
【问题讨论】:
-
你为什么要这样做?
-
您应该将代码提取到更多方法中,而不是相反。
-
@ScaryWombat 这是一个任务。我被要求删除该方法。
-
我同意@Tom 所说的。 Google for 一个函数应该做一件事
-
是的,在现实生活中,这个特定的功能应该保持独立。但是,有时将功能结合在一起是有意义的,而 Shibaku 的任务就是在那个时候练习。