Results 1 to 7 of 7
Thread: problem with if statement?
- 04-24-2012, 04:00 AM #1
Member
- Join Date
- Apr 2012
- Posts
- 25
- Rep Power
- 0
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)
The problem is, the program never outputs the position if the word already exists - only 0s; to take the example from before: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(); } } }
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.
- 04-24-2012, 04:47 AM #2
Senior Member
- Join Date
- Apr 2012
- Location
- New York State of Confusion, USA
- Posts
- 137
- Blog Entries
- 1
- Rep Power
- 0
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.]
- 04-24-2012, 04:56 AM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
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.
So I would write a method that does just that. (and just that)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.
Then I would test it: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 ... }
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".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 ... } }
- 04-24-2012, 06:56 AM #4
Member
- Join Date
- Apr 2012
- Posts
- 25
- Rep Power
- 0
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:
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.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(); } } }
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.
- 04-24-2012, 11:53 AM #5
Senior Member
- Join Date
- Apr 2012
- Location
- New York State of Confusion, USA
- Posts
- 137
- Blog Entries
- 1
- Rep Power
- 0
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.
That will put quotes around each string. If three's a newline character in one of them, it should become obvious.Java Code:System.out.println(String.format("'%s' '%s'", arr[i], str)); //test whether duplicates are found by printing them to the terminal
- 04-25-2012, 02:36 AM #6
Member
- Join Date
- Apr 2012
- Posts
- 25
- Rep Power
- 0
Re: problem with if statement?
Thank you for your input, jlczuk.
If I take this code:
..and replace it with:Java Code:for(int i = 0; i < wordCount; i++){
..I get:Java Code:for(int i = 0; i < arr.length; i++){
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:
I replaced it with:Java Code:wordList = temp;
The program is working exactly how I want it to now. Thanks again for everyone's input.Java Code:wordList = new String[temp.length]; for(int i = 0; i<temp.length;i++){ wordList[i] = temp[i]; }Last edited by cherrychives; 04-25-2012 at 06:17 AM.
- 04-25-2012, 02:42 AM #7
Senior Member
- Join Date
- Apr 2012
- Location
- New York State of Confusion, USA
- Posts
- 137
- Blog Entries
- 1
- Rep Power
- 0
Similar Threads
-
sql statement problem
By vincentcharrie in forum EclipseReplies: 5Last Post: 02-16-2012, 03:41 PM -
Problem with if statement
By SiX in forum New To JavaReplies: 8Last Post: 07-22-2011, 07:49 PM -
Problem with if statement - Char
By KardKaper in forum New To JavaReplies: 8Last Post: 12-22-2009, 01:14 PM -
If-Else statement problem
By MomenT in forum New To JavaReplies: 9Last Post: 10-23-2008, 08:06 AM -
Please help me with this Problem Statement
By KMS in forum New To JavaReplies: 1Last Post: 09-22-2008, 08:44 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks