2

ユーザーに 3 つの単語を入力して辞書順で並べ替えるように求めるプログラムを作成しようとしています。

例;

  • 3 つの単語をスペースで区切って入力してください:
  • ペア オレンジ アップル
  • アップル
  • オレンジ

以下に示す 1 つのタイプの組み合わせの例を除いて、プログラムは正常に動作しています (上記の例を試した場合)。

例;

  • 3 つの単語をスペースで区切って入力してください:
  • オレンジアップルペア
  • アップル

最初の単語 (オレンジ) が 3 つの単語の途中に表示されるはずの場合、プログラムはそれをスキップしています。

「この割り当てられた値は決して使用されない」と書かれているため、このコード行がプログラムに影響を与えていると思いますが、私はまだ初心者の Java 学習者であるため、修正方法がわかりません。

  • 中央 = 最初の単語;

そのセリフが使われなくなったせいで、ペアが2回登場した。

import java.util.*;
public static void main(String[] args) 
{

Scanner wordInput = new Scanner(System.in);
String firstWord;
String secondWord;
String thirdWord;


System.out.println("Enter three words separated by spaces: ");

firstWord = wordInput.next();
secondWord = wordInput.next();
thirdWord = wordInput.next();


String top = firstWord;
String bottom = firstWord;
if( top.compareTo(secondWord) > 0) 
{ 
top = secondWord; 
} 
if( top.compareTo(thirdWord) > 0) 
{ 
top = thirdWord; 
} 
if( bottom.compareTo(secondWord) < 0) 
{ 
bottom = secondWord; 
} 
if( bottom.compareTo(thirdWord) < 0) 
{ 
bottom = thirdWord; 
}   
String middle;
if( !firstWord.equals(bottom) && !firstWord.equals(top) ) 
{ 
middle = firstWord; 
} 
if( !secondWord.equals(bottom) && !secondWord.equals(top) ) 
{ 
middle = secondWord; 
} 
else 
{ 
middle = thirdWord; 
} 

System.out.println( top ); 
System.out.println( middle ); 
System.out.println( bottom ); 


}
}

私が行方不明または間違っていることはありますか? :(助けてくれてありがとう!

4

3 に答える 3

0

コードの少ない別のソリューションを次に示します

public static void main(String[] args) {
    // TODO code application logic here
    System.out.println("Enter three words separated by spaces: ");
    //Scanner wordsInput = new Scanner(System.in);
    Console console = System.console();

    //List<String> words = new ArrayList<>();
    List<String> words = Arrays.asList(console.readLine().split("\\s+"));
    Collections.sort(words);
    for (String word : words) {
         System.out.println(String.format("- %s",word));
    }
}
于 2013-10-20T03:50:38.897 に答える