Back to General discussions forum
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.
Write a program which sieves necessary words from the given text, and prints them in the proper order.
Write a program which sieves necessary words from the given text, and prints them in the proper order.
Thank for your help, smwentum! I do this.
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!