Results 1 to 3 of 3
Thread: comparing
- 11-23-2007, 12:26 AM #1
Member
- Join Date
- Nov 2007
- Posts
- 13
- Rep Power
- 0
comparing
I want to check which words that i read from an input text file (one word per line) do not occur in an array of strings (that I already have in my program). I used the .equals to compare the word to every word of my array. Then when I print (everytime a word does not occur in in the array) I see e.g. 10 times (=number of elements in the array) the phrase ("The word" + fileLine+ "does not occur."). What should I do? When using arrays there is no 'boolean contains ();'
Last edited by Feng; 11-23-2007 at 08:01 AM.
- 11-23-2007, 01:22 AM #2
Member
- Join Date
- Nov 2007
- Posts
- 8
- Rep Power
- 0
If its an array of Strings, why dont you use String comparision. If not post sample code and it will help us to understand your problem and help u.
- 11-23-2007, 10:40 AM #3Java Code:
import java.io.*; import java.util.*; public class ComparingStrings { static String[] words = { "green", "blue", "cyan", "magenta", "orange", "black" }; public static void main(String[] args) { String path = "wordsToRead.txt"; StringBuilder sb = new StringBuilder(); try { Scanner scanner = new Scanner(new File(path)); while(scanner.hasNextLine()) { sb.append(scanner.nextLine() + " "); } scanner.close(); } catch(FileNotFoundException e) { System.out.println("File not found " + e.getMessage()); } String[] fileWords = sb.toString().split("\\s"); String[] extraWords = getNewWords(fileWords); System.out.printf("extra words = %s%n", Arrays.toString(extraWords)); } private static String[] getNewWords(String[] allWords) { List<String> newWords = new ArrayList<String>(); for(int j = 0; j < allWords.length; j++) { if(!isInWords(allWords[j]) && !newWords.contains(allWords[j])) newWords.add(allWords[j]); } return newWords.toArray(new String[newWords.size()]); } private static boolean isInWords(String s) { for(int j = 0; j < words.length; j++) { if(words[j].equals(s)) return true; } return false; } }
Similar Threads
-
Comparing Images
By shaungoater in forum Advanced JavaReplies: 0Last Post: 03-17-2008, 11:38 AM -
Comparing dates
By Java Tip in forum Java TipReplies: 0Last Post: 01-28-2008, 10:02 AM -
Comparing problem
By mcal in forum New To JavaReplies: 1Last Post: 01-24-2008, 04:56 AM -
Comparing JavaWebFrameworks
By pegitha in forum Web FrameworksReplies: 1Last Post: 05-18-2007, 07:23 PM
Bookmarks