-2

以下のプログラムを作成して、入力文字列を並べ替え、辞書式順序で並べ替えたリストを出力します。

問題があるようですが、誰かが私にそれを見つけるのを手伝ってもらえますか?

import java.util.ArrayList;
import java.util.Scanner;

public class Problem3 
{
    public static void main(String[] args) 
    {
        Scanner scanner = new Scanner(System.in);
        String statement = scanner.nextLine();
        screen(statement);
    }
    public static void screen(String statement)  // sorting mechanism 
    {
        String token[]= statement.split(" ");
        String smallestSoFar=token[0]; 
        ArrayList<String> list = new ArrayList<String>();
        for(int i=0; i<token.length;i++)
        {
            smallestSoFar=token[i];
            for(int e=i; e<token.length; e++)
            {
                if(token[e].compareTo(smallestSoFar)<0)  // inputting the // ...lexicographically sorted word into a new list
                {
                    smallestSoFar=token[e]; 
                    list.add(smallestSoFar);                
                }
            }
            System.out.println(list);
        }           
    }    
}
4

1 に答える 1

1

問題は、要素の後に小さな要素が続く場合、それが出力されないことです (そして、大きな要素が 2 回出力されます)。そして、あなたのプリントは間違った場所にあります(ループの後でなければなりません)。

簡単に使用できます

Arrays.sort(token)

また

list = new ArrayList<String>(Arrays.asList(token));
Collections.sort(list);

配列をソートします。

自分のやり方に固執したい場合は、次のようにします。

boolean[] checked = new boolean[token.length];
int checkedCount = 0;
while (checkedCount < token.length)
{
    int smallestIndex = -1;
    for(int i = 0; i < token.length; i++)
    {
        if (!checked[i] &&
            (smallestIndex == -1 || token[i].compareTo(token[smallestIndex]) < 0))
        {
            smallestIndex = i;
        }
    }
    checked[smallestIndex] = true;
    checkedCount++;
    list.add(token[smallestIndex]);
}
System.out.println(list);
于 2013-02-20T19:49:17.097 に答える