我目前正处于第一学期。我有一个项目要求我构建一个用户输入3个单词的程序,按字母顺序排序并输出中间单词。我做了一些搜索,似乎只回来结果排序2个单词。到目前为止我有代码来获取用户输入,但我完全迷失了如何按字母顺序对它们进行排序以及如何提示用户输入三个字符串。请耐心等待我,因为我对编程很陌生。如果有人可以向我提供任何建议或最好或最简单的方法来分类这些我会非常感激
import java.util.Scanner; //The Scanner is in the java.util package.
public class MiddleString {
public static void main(String [] args){
Scanner input = new Scanner(System.in); //Create a Scanner object.
String str1, str2, str3;
System.out.println("Please enter one word words : "); //Prompt user to enter one word
str1=input.next(); //Sets "str1" = to first word.
str2=input.next(); //Sets "str2" = to second word.
str3=input.next(); //Sets "str3" = to third word.
System.out.println("The middle word is " ); // Outputs the middle word in alphabetical order.
}
}
请帮忙!
答案 0 :(得分:1)
尝试这样的事情:
String [] strings;
int i = 0;
System.out.println("Please enter one word words : "); //Prompt user to enter one word
strings[i++] = input.next(); //Sets "str1" = to first word.
strings[i++] = input.next(); //Sets "str2" = to second word.
strings[i++] = input.next(); //Sets "str3" = to third word.
Arrays.sort(strings);
System.out.println("The middle word is " + strings[strings.length / 2]);
答案 1 :(得分:0)
您可以一次只对两个单词进行排序(比较),是的,但这是整个排序算法的基础。你需要遍历你的单词数组,并将每个单词与其他单词进行比较。
String[2] words = new String[2];
words[0] = input.next();
words[1] = input.next();
words[2] = input.next();
String[2] sortedWords = new String[2];
for (String word: words){ // outer loop
for (String word: words){ // inner loop to compare each word with each other
// logic to do the comparisons and sorting goes here
}
}
System.out.println(sortedWords[1]);
当然,我已经为你省去了有趣的部分,但这应该让你开始。