# Boolean and String Trouble...

• November 2nd, 2012, 11:33 PM
Souljahgirl101
Boolean and String Trouble...
ok, so the general assignment is to create a class called SearchMyString and its driver that allows the user to enter any word or words that they want, and then choose to find the number of vowels, find the number of words, and search their entry for any word (which will either tell them the word is found in their original entry, or not). i know, very simple, but i am only in a high school computer programming class; give me a break. what i am having trouble with is creating the third method (searching their entry). the teacher told us that we need to use boolean for it, obviously, but i'm not quite sure how to make it work in my code because every time i compile, something is wrong (i am using blue j, by the way). i have been working on this for hours, and i just really need some help on this! if you could explain to me how to do it (not just do it for me, please), that would be amazing! thank you!

THIS IS MY ORIGINAL CLASS CODE:

Code :

```import java.util.Scanner; public class SearchMyString { public String userStr; Scanner in = new Scanner(System.in);   public SearchMyString(String userStr) { this.userStr = userStr; }```

here are the choices the user has:

Code :

``` public void displayMenu() { System.out.print("What would you like to do with your entry?\n"); System.out.print("(1) Find Vowels\n"); System.out.print("(2) Find Number of Words\n"); System.out.print("(3) Search Word\n"); }```

method to find vowels (im finished with this already):

Code :

``` public int findVowels() { int counter = 0; System.out.print("==============================\n\n"); for(int i = 0; i < userStr.length(); i++) { if(userStr.charAt(i) == 'a') { System.out.print("a is at position " + i + "\n"); counter++; }else if(userStr.charAt(i) == 'e') { System.out.print("e is at position " + i + "\n"); counter++; }else if(userStr.charAt(i) == 'i') { System.out.print("i is at position " + i + "\n"); counter++; }else if(userStr.charAt(i) == 'o') { System.out.print("o is at position " + i + "\n"); counter++; }else if(userStr.charAt(i) == 'u') { System.out.print("u is at position " + i + "\n"); counter++; }else if(userStr.charAt(i) == 'y') { System.out.print("y is at position " + i + "\n"); counter++; } }//looks for only vowels. if found, adds +1 to counter System.out.print("Number of vowels = " + counter + "\n\n"); System.out.print("==============================\n\n"); return(counter); }```

the method to find the number of words (finished this, too):

Code :

``` public int findNumOfWords() { int numWords = 0; System.out.print("==============================\n\n"); for(int i = 0; i < userStr.length(); i++) { if(userStr.charAt(i) == ',') {//if the character is "," numWords++;//+1 to numWords (if true) }else if(userStr.charAt(i) == '.') {//if the character is "." numWords++;//+1 to numWords (if true) } } System.out.print("Number of words = " + numWords + "\n\n"); System.out.print("==============================\n\n"); return(numWords); }```

AAAAAND here's where the trouble starts... i am so lost:

Code :

``` public boolean searchWord(String srchTerm) { for(int i = 0; i < userStr.length(); i++) { if(srchTerm.charAt(i) == userStr.charAt(i)) { boolean srch = true; break; }else { boolean srch = false; break; } } if(true) { System.out.print("That word was found!\n\n"); }else if(false) { System.out.print("That word was not found.\n\n"); } System.out.print("==============================\n\n"); return(srch); } }```

THIS IS MY DRIVER CLASS CODE (in case any of this matters...):

Code :

```import java.util.Scanner; public class SearchMyStringTest { public static void main(String args[]){   while(true){ Scanner in = new Scanner(System.in); System.out.print("Enter Your Words! (Separate with commas (,) End with period (.))\n"); String userInput = in.nextLine();//receives the user input SearchMyString str = new SearchMyString(userInput);//holds the user input   str.displayMenu(); int ans = in.nextInt();   if(ans == 1){ int counter = str.findVowels(); }else if(ans == 2){ int numWords = str.findNumOfWords(); }else if(ans == 3){ System.out.print("==============================\n\n"); System.out.print("Please enter the word you would like to search for:\n\n"); String word = in.nextLine(); SearchMyString newSearch = new SearchMyString(word); int srch = str.searchWord(word); }   System.out.print("Would you like to play again?\n"); System.out.print("1. Yes\n"); System.out.print("2. No\n"); int c = in.nextInt();   if(c == 1){ System.out.print("==============================\n\n"); }else if(c == 2){ System.out.print("==============================\n\n"); System.out.print("Thanks for playing!\n\n"); System.out.print("==============================\n\n"); break; } } } }```

thank you so much!!!
• November 2nd, 2012, 11:51 PM
pbrockway2
Re: Boolean and String Trouble...
Quote:

every time i compile, something is wrong
Perhaps you could be a little bit more descriptive :)

What are the compiler messages associated with the searchWord() code you posted?

---

Also I notice something a bit odd with the methods you have already written. Take findNumOfWords() as an example. It calculates and returns the number of words. But - and this is what I would question - it also prints stuff.

Generally a method does just one thing. If it is a method that returns something (like the number of words), then that is what it should do. The caller of the method (the driver) should do what it likes with the returned value - in this case do the System.out.println() stuff. At the moment in the driver you say:

Code :

```}else if(ans == 2){ int numWords = str.findNumOfWords(); }```

This creates a numWords variable, assigns a value to it and then ... throws the variable (value and all) away. This seems a bit pointless. (Remember that after the } the variable will no longer exist).

Read your assignment instructions carefully. Have the methods do what they are supposed to and no more. It is very common in thi sort of question to be told not to have output in the methods, but, of course, I haven't seen your assignment.
• November 3rd, 2012, 12:33 AM
Souljahgirl101
Re: Boolean and String Trouble...
i know normally the methods do not print anything in them, but for the sake of the assignment, my teacher just told us to put it all inside the method.

and the compiler messages just say "cannot find symbol - variable srch"... i think this is because it is in the for loop and no where outside of it, but when i try to initialize it at the beginning of the method, like this...

Code :

```public boolean searchWord(String srchTerm) { boolean srch; for(int i = 0; i < userStr.length(); i++) { if(srchTerm.charAt(i) == userStr.charAt(i)) { boolean srch = true; break; }else { boolean srch = false; break; } } if(true) { System.out.print("That word was found!\n\n"); }else if(false) { System.out.print("That word was not found.\n\n"); } System.out.print("==============================\n\n"); return(srch); }```

the error message says "variable srch is already defined in method searchWord(java.lang.String)" i just want the method to be able to search through the user's original sentence for the word they entered that they want to search for, and if its found, it says it is, and if not, then its opposite.
• November 3rd, 2012, 12:58 AM
pbrockway2
Re: Boolean and String Trouble...
Quote:

my teacher just told us to put it all inside the method
Then your teacher is guilty of inelegance and stupidity. Much the same thing in the long run: as the complexity of the code grows the former grows inevitably into the latter.

Not your fault. But, in any case, document the method to say that it does this (foolish, inelegant) thing:

Code :

``` /** * Prints a message about the number of words and returns this value. */ public int findNumOfWords() { // etc }```

Also remove the unnecessary variable declared in the driver:

Code :

```}else if(ans == 2){ //int numWords = str.findNumOfWords(); str.findNumOfWords(); }```

---

You are quite right about the meaning of the messages. Remember that variables only really exist from the point where they are declared until the end of the {---} block they are declared in. So if you want to use the variable outside the if and else blocks it will have to be declared before the if statement. The thing is that, having declared it you cannot declare it again.

Code :

```boolean srch; for(int i = 0; i < userStr.length(); i++) { if(srchTerm.charAt(i) == userStr.charAt(i)) { //boolean srch = true; srch = true; break; }else { //boolean srch = false; srch = false; break; } } if(true) { System.out.print("That word was found!\n\n"); }else if(false) { System.out.print("That word was not found.\n\n"); } System.out.print("==============================\n\n"); return(srch);```
• November 3rd, 2012, 02:05 AM
Souljahgirl101
Re: Boolean and String Trouble...
ok... you are seriously miracle worker.... :o i fixed all the code, and it compiles now! i also moved the printers to the driver class. :) the new code looks like this:

Code :

```public boolean searchWord(String srchTerm) { boolean srch = false;//initializes srch variable for(int i = 0; i < userStr.length(); i++) { if(srchTerm.charAt(i) == userStr.charAt(i)) { srch = true;//redefines srch break; }else { srch = false;//redefines srch } } return(srch); }```

AND:

Code :

```if(ans == 1){ System.out.print("==============================\n\n"); System.out.print("Number of vowels = " + str.findVowels() + "\n\n"); System.out.print("==============================\n\n"); }else if(ans == 2){ System.out.print("==============================\n\n"); System.out.print("Number of words = " + str.findNumOfWords() + "\n\n"); System.out.print("==============================\n\n"); }else if(ans == 3){ System.out.print("==============================\n\n"); System.out.print("Please enter the word you would like to search for:\n\n"); String word = in.nextLine();//allows user input SearchMyString newSearch = new SearchMyString(word);//allocates memory for user input if(str.searchWord(word) == true)//if term was found { System.out.print("That word was found!\n\n"); }else if(str.searchWord(word) == false)//if term was not found { System.out.print("That word was not found.\n\n"); } System.out.print("==============================\n\n"); }```

BUT... now there is a new problem... i ran the program to test it and it came up with another error... it says "java.lang.StringIndexOutOfBoundsException: String index out of range: 0 (in java.lang.String)"... another note, when i ran the program, it allowed me to enter my choice from the menu, but when i entered "3", it displayed everything up to "Please enter the word you would like to search..." and it would not let me enter the word i wanted to search for. instead, it simply displayed the error, and highlights just this part of the code: "if(srchTerm.charAt(i) == userStr.charAt(i))". so, i am assuming there is something wrong with that...
• November 3rd, 2012, 08:17 PM
pbrockway2
Re: Boolean and String Trouble...
The printing looks good :)

Now if you are getting a "String index out of range: 0" message from the line "if(srchTerm.charAt(i) == userStr.charAt(i))" it looks very much as if you are checking userStr at an "illegal" position. I mean at a position beyond where the string ends. It would be a good plan to check what the value of userStr really is:

Code :

```public boolean searchWord(String srchTerm) { System.out.println("Searching for -->|" + srchTerm + "|<--"); boolean srch = false;//initializes srch variable for(int i = 0; i < userStr.length(); i++) { if(srchTerm.charAt(i) == userStr.charAt(i)) { srch = true;//redefines srch break; }else { srch = false;//redefines srch } } return(srch); }```

The reason for the arrows and things is that I'd wonder about the search term being an empty string. (And the reason for that was the zero mentioned in the exception as being the invalid character position. The only string that doesn't have a zero position is the empty string.)

Try that and see what you are searching for.

---

Really do run the code above! Otherwise what follows will be a spoiler.

The while loop of your driver looks like this:

Code :

```Scanner in = new Scanner(System.in); System.out.print("Enter Your Words! (Separate with commas (,) End with period (.))\n"); String userInput = in.nextLine();//receives the user input SearchMyString str = new SearchMyString(userInput);//holds the user input   str.displayMenu(); int ans = in.nextInt(); /* ===A=== */   if(ans == 1){ // ... }else if(ans == 2){ // ... }else if(ans == 3){ System.out.print("==============================\n\n"); System.out.print("Please enter the word you would like to search for:\n\n"); String word = in.nextLine(); /* ===B=== */ SearchMyString newSearch = new SearchMyString(word); int srch = str.searchWord(word); // ... } // ...```

The nextInt() call on the line I've marked A is interesting. It reads and returns an int. But, more subtly, it leaves the scanner pointing just past where the int ends. Ie it leaves the scanner just before the new line. And this has an unfortunate consequence: when, at the line I've marked B, you call nextLine() you will get an empty string returned. That's because nextLine() returns everything up to the newline (which will be nothing) and then skips over the new line.

(Moreover nextLine() will return the empty string straight away. It won't wait for anything to be entered.)

The fix depends on this behaviour of nextLine() - on the fact that it skips over the newline. It is to put a nextLine() call just after the nextInt().

Code :

```Scanner in = new Scanner(System.in); System.out.print("Enter Your Words! (Separate with commas (,) End with period (.))\n"); String userInput = in.nextLine();//receives the user input SearchMyString str = new SearchMyString(userInput);//holds the user input   str.displayMenu(); int ans = in.nextInt(); /* ===A=== */ in.nextLine(); // advance to the next line   // ...```