Results 1 to 7 of 7
  1. #1
    cherrychives is offline Member
    Join Date
    Apr 2012
    Posts
    25
    Rep Power
    0

    Default problem with if statement?

    I am writing a program in java which reads a text file, (textfile.txt in this case), and stores the word in the 0th(first) position of an array (wordList), then outputs the contents to another text file (newtextfile.txt), one word at a time. If the word is a new word, the output will read "0 word", otherwise it outputs the first position the word was found in the array.

    For example:
    If s = "frog", and frog does not exist at all in the wordList, the output will be "0 frog"
    If s = "the", and also wordlist[5] = "the", then the output will be "5 the" (even if there are more instances of "the" in the array, as I only want the position of the first instance)

    Java Code:
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.util.Scanner;
    import java.util.StringTokenizer;
    
    class myProgram{
    	private static Scanner scan;
    	private static StringTokenizer st;
    	private static String[] wordList;
    	private static String[] temp;
    	private static int[] indexArr;
    	private static int index;
    
    	public static void main(String [] args){
    		try{
    			String stringCount = null;			
    			String s = null;
    			int wordCount = 0;
    			scan = new Scanner(new FileReader("textfile.txt"));
    			PrintWriter out = new PrintWriter(new FileWriter("newtextfile.txt"));
    			while(scan.hasNext("\\S+")) {
    				stringCount = scan.next("\\S+");
    				wordCount++;
    			}
    			wordList = new String[wordCount];
    			temp = new String[wordCount];
    			indexArr = new int[wordCount];
    			wordCount = 0;
    			scan = new Scanner(new FileReader("textfile.txt"));
    			while(scan.hasNextLine()){
    				st = new StringTokenizer(scan.nextLine());
    					while(st.hasMoreTokens()){
    						s = st.nextToken();
    						for(int i = 0; i < wordCount; i++){
    							if(wordList[i].equals(s)){ // < problem here?
    								index = i;
    								break;
    							}
    							else{
    								index = 0;
    							}
    						}
    						temp[0] = s;
    						for(int i = 0; i < wordCount; i++){
    							temp[i+1] = wordList[i];
    						}
    						wordList = temp;
    						out.println(index + " " + wordList[0]);
    						wordCount++;
    					}
    			}
    			out.close();
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    }
    The problem is, the program never outputs the position if the word already exists - only 0s; to take the example from before:

    If s = "the", and also wordlist[5] = "the", I need the output to be "5 the", but instead it outputs "0 the".

    I figure this means my if statement, if(wordList[i].equals(s)) isn't correct. But I can't figure out what I'm doing wrong.

    Any advice is much appreciated.
    Last edited by cherrychives; 04-25-2012 at 02:29 AM.

  2. #2
    jlczuk is offline Senior Member
    Join Date
    Apr 2012
    Location
    New York State of Confusion, USA
    Posts
    137
    Blog Entries
    1
    Rep Power
    0

    Default Re: problem with if statement?

    What you should do is in the for loop at line 37, just before that if, print out the two things you are comparing. Then you will see what the compare operation sees and it will give you a clue as to what might be wrong.

    [Edit to correct line number from 7 to 37.]

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: problem with if statement?

    Perhaps it would help to break things into multiple methods...

    I'm tired - and lazy - so I'm having trouble following that lengthy, nested main(). It's been my experience that tired leads to errors, but that lazy leads to simplicity and thereby valid code.

    If the word is a new word, the output will read "0 word", otherwise it outputs the first position the word was found in the array.
    So I would write a method that does just that. (and just that)

    Java Code:
        /** Returns the index of the first occurance of a word.  Or zero if not found. */
    private static int indexOf(String[] arr, String target) {
        // <your code here>
        // return ...
    }
    Then I would test it:

    Java Code:
    class MyProgram {
        public static void main(String[] args) {
            String[] arr = {"the", "quick", "brown", "frog", "brown"};
    
            System.out.println(indexOf(arr, "quick")); // expect 1
            System.out.println(indexOf(arr, "brown")); // expect 2
            System.out.println(indexOf(arr, "dog")); // expect 0
            System.out.println(indexOf(arr, "the")); // expect 0
    
        }
    
            /** Returns the index of the first occurance of a word.  Or zero if not found. */
        private static int indexOf(String[] arr, String target) {
            // <your code here>
            // return ...
        }
    }
    And so on through all of the steps that need to be done. (Populating the array from the file. Figuring out the output strings, perhaps in an array. Writing the output file. Etc). By making each method do just one thing it can be tested as you go. The alternative is to be mystified when the output is wrong. For example you say "if(wordList[i].equals(s)){ // < problem here?" but that is a straight forward test of whether a string in the array is equal to some given string. There is nothing problematic with that line per se: if anything, it's how it's used. Numerous small methods help to clarify the "plan of attack".

  4. #4
    cherrychives is offline Member
    Join Date
    Apr 2012
    Posts
    25
    Rep Power
    0

    Default Re: problem with if statement?

    Thank you, pbrock. Your input is appreciated.

    Sorry about the code; I know it's a mess. I've tidied it up a little by doing what you said:

    Java Code:
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.util.Scanner;
    import java.util.StringTokenizer;
    
    class myProgram{
    	private static StringTokenizer st;
    	private static String[] wordList;
    	private static String[] temp;
    	private static int[] indexArr;
    	private static int index;
    	private static int wordCount;
    
    	private static int indexOf(String[] arr, String str){
    		for(int i = 0; i < wordCount; i++){
    			if(arr[i].compareTo(str) == 0){
    				System.out.println(arr[i] + str); //test whether duplicates are found by printing them to the terminal
    				return i; //return current position in array if the word is found
    			}
    		}
    		return 0; //return 0 if word is not found in the array
    	}
    
    	public static void main(String [] args){
    		try{
    			String stringCount = null;			
    			String s = null;
    			wordCount = 0;
    			boolean hasElement = false;
    			Scanner scan = new Scanner(new FileReader("textfile.txt"));
    			PrintWriter out = new PrintWriter(new FileWriter("newtextfile.txt"));
    			while(scan.hasNext()) {
    				stringCount = scan.next("\\S+"); //point to next item in scan (with space " " as delimiter)
    				wordCount++; //increment wordCount
    			}
    			wordList = new String[wordCount];
    			temp = new String[wordCount];
    			indexArr = new int[wordCount];
    			wordCount = 0;
    			scan = new Scanner(new FileReader("textfile.txt"));
    			while(scan.hasNextLine()){
    				st = new StringTokenizer(scan.nextLine());
    					while(st.hasMoreTokens()){
    						s = st.nextToken();
    						index = indexOf(wordList, s);
    						temp[0] = s; //set the first value in temp array to s
    						for(int i = 0; i < wordCount; i++){
    							temp[i+1] = wordList[i]; //add wordList array values to temp array
    						}
    						wordList = temp; //replace wordList values with temp array values
    						out.println(index + " " + wordList[0]);
    						wordCount++;
    					}
    			}
    			out.close();
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    }
    It's still doing the exact same thing, except the System.out.println(arr[i] + str); in the indexOf method seems to only output to the terminal when a word is repeated right after itself.

    For example, if textfile.text contains the following:

    she is still still
    she is still still

    ..it will output the following to the terminal:

    still still
    still still

    ..and newtextfile.txt will receive this:

    0 she
    0 is
    0 still
    0 still
    0 she
    0 is
    0 still
    0 still

    I think the problem is that the for loop continues to loop even after passing through the return i; statement. In other words, return i; is being ignored, so the method still returns 0, regardless. How do I fix that?

    This is extremely perplexing..
    Last edited by cherrychives; 04-25-2012 at 06:18 AM.

  5. #5
    jlczuk is offline Senior Member
    Join Date
    Apr 2012
    Location
    New York State of Confusion, USA
    Posts
    137
    Blog Entries
    1
    Rep Power
    0

    Default Re: problem with if statement?

    At line 16, you should use the size of the array instead of a separate variable. That's and index out-of-bounds exception waiting to happen.

    It is skipping the return because one of your strings probably has a non-printable character like a newline attached to hit. In cases like this example, I would normally use something like this to 'see' what exactly is being compared. Alternatively, you could try editing your textfile.text and remove the newline after "she is still still" and see what happens. I would also read the API documentation for the Scanner class carefully to understand what it's behavior is with newlines and with the end-of-file.

    Java Code:
    System.out.println(String.format("'%s' '%s'", arr[i], str)); //test whether duplicates are found by printing them to the terminal
    That will put quotes around each string. If three's a newline character in one of them, it should become obvious.

  6. #6
    cherrychives is offline Member
    Join Date
    Apr 2012
    Posts
    25
    Rep Power
    0

    Default Re: problem with if statement?

    Thank you for your input, jlczuk.

    If I take this code:

    Java Code:
    for(int i = 0; i < wordCount; i++){
    ..and replace it with:

    Java Code:
    for(int i = 0; i < arr.length; i++){
    ..I get:

    java.lang.NullPointerException
    at myProgram.indexOf(scanner.java:17)
    at myProgram.main(scanner.java:45)

    Which is why I created the wordCount variable in the first place. It seems to work fine.

    I found that my problem was at line 51:

    Java Code:
    wordList = temp;
    I replaced it with:

    Java Code:
    wordList = new String[temp.length];
    for(int i = 0; i<temp.length;i++){
    	wordList[i] = temp[i];
    }
    The program is working exactly how I want it to now. Thanks again for everyone's input.
    Last edited by cherrychives; 04-25-2012 at 06:17 AM.

  7. #7
    jlczuk is offline Senior Member
    Join Date
    Apr 2012
    Location
    New York State of Confusion, USA
    Posts
    137
    Blog Entries
    1
    Rep Power
    0

    Default Re: problem with if statement?

    Excellent, glad it's working. In the code example I posted, I was not giving you the exact answer. It was only an example to illustrate my point. I'm glad you figured that out and were able to make the proper correction.

Similar Threads

  1. sql statement problem
    By vincentcharrie in forum Eclipse
    Replies: 5
    Last Post: 02-16-2012, 03:41 PM
  2. Problem with if statement
    By SiX in forum New To Java
    Replies: 8
    Last Post: 07-22-2011, 07:49 PM
  3. Problem with if statement - Char
    By KardKaper in forum New To Java
    Replies: 8
    Last Post: 12-22-2009, 01:14 PM
  4. If-Else statement problem
    By MomenT in forum New To Java
    Replies: 9
    Last Post: 10-23-2008, 08:06 AM
  5. Please help me with this Problem Statement
    By KMS in forum New To Java
    Replies: 1
    Last Post: 09-22-2008, 08:44 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •