MatchingWords (task 55)

Back to General discussions forum

Alexandr Bondarev     2015-03-22 17:57:51

What's wrong in this code? (for Matching Words problem)

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

public class MatchingWords{

    public static void main(String[] args){
        Scanner scr = new Scanner(System.in);
        String data = scr.nextLine();
        String answer = matchingWords(data);
        System.out.println(answer);
    }

    public static String matchingWords(String str){
        String result = new String();

        String[] tmp = str.split(" ");
        ArrayList<String> list = new ArrayList(Arrays.asList(tmp));

        while (true){
            String compar = list.get(0);
            if (compar.equals("end"))
                break;

            list.remove(0);

            if (list.contains(compar)){
                result += compar + " ";
                list.remove(compar);
            }
        }

        return result;
    }
}

when I give as input example in problem answer matches.

P.S. Sorry for my bad English.

smwentum     2015-03-22 22:46:39

Write a program which sieves necessary words from the given text, and prints them in the proper order.

smwentum     2015-03-22 22:48:26

Write a program which sieves necessary words from the given text, and prints them in the proper order.

Alexandr Bondarev     2015-03-23 09:16:49

Thank for your help, smwentum! I do this.

Rodion (admin)     2015-03-23 10:32:40
User avatar

Alexandr, thanks for your question! You hinted me to change example in the problem so that it does not yield proper answer without sorting. Hope this will help other people! :)

And also thanks to our colleague smwentum for fast answer!

Please login and solve 5 problems to be able to post at forum