Results 1 to 6 of 6
  1. #1
    NickB750 is offline Member
    Join Date
    Apr 2016
    Posts
    3
    Rep Power
    0

    Default java problem with for-loop

    I'm practicing for loops in eclipse and am encountering an issue with my code.

    Java Code:
    public class JavaPractice {
    	// methods must be declared outside of the main method...
    	// why would you declare a method in another method...?
    		
    	static String textSearch(String query, String text) {
    		int hit = 0;
    		
    		for(int i = 0; i < text.length(); i++) {
    			if(text.substring(i, i + query.length() ) == query) {
    				hit += 1;
    				return "";
    			}
    			System.out.println("# of '" + query + "' found: " + hit);
    			
    			
    		}
    		return "";
    	}
    	
    	public static void main(String[] args) {
    		String story = "There was a man named Bob who"
    				+ "was fascinated by his name - Bob. "
    				+ "He said the name 'Bob' to himself"
    				+ "many times a day to emphasize its"
    				+ "generic qualities. ";
    		
    		System.out.println(textSearch("Bob", "Bob saw a Bob"));
    		
    		
    	}
    }
    Apart from the console error below, indicating problems on lines 9 and 27 :

    # of 'Bob' found: 0
    # of 'Bob' found: 0
    # of 'Bob' found: 0
    # of 'Bob' found: 0
    # of 'Bob' found: 0
    # of 'Bob' found: 0
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 14
    at java.lang.String.substring(Unknown Source)
    at JavaPractice.textSearch(JavaPractice.java:9)
    at JavaPractice.main(JavaPractice.java:27)

    I have no idea what the problem is. Any help would be appreciated!

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,807
    Rep Power
    12

    Default Re: java problem with for-loop

    Don't compare Strings with ==, use the equals method instead.

  3. #3
    NickB750 is offline Member
    Join Date
    Apr 2016
    Posts
    3
    Rep Power
    0

    Default Re: java problem with for-loop

    Thank you. I fixed that and made some other changes as of the original code:

    Java Code:
    public class JavaPractice {
    	
    	static String textSearch(String query, String text) {
    		int hit = 0;
    		text = text + "!@#$%^&*()";
    		// if i gets to the points where there is no more text,
    		// the loop can't check if there's a query (there can't be
    		// because would be no more text)
    		for(int i = 0; i < text.length(); i++) {
    			
    			if(text.substring(text.length() - 9, text.length()).equals("!@#$%^&*()")) {
    					break;
    			} 
    			else if(text.substring(i, i + query.length() ).equals(query)) {
    				// if the counter reaches past text length minus query length
    				
    				if( ( text.substring(text.length() - query.length()) ).length() > ( query.length() ) ) {
    					// set i to the length of the text to end the loop
    					i = text.length();
    				}
    				hit += 1;
    				System.out.println("# of '" + query + "' found: " + hit);
    			}
    				
    		}
    		return "";
    	}
    	
    	public static void main(String[] args) {
    		String story = "There was a man named Bob who"
    				+ " was fascinated by his name - Bob. "
    				+ " He said the name 'Bob' to himself"
    				+ " many times a day to emphasize its"
    				+ " generic qualities. ";
    		
    		
    		
    		// miscellaneous code vvv
    		System.out.println(story.length());
    		
    		// method call		  vvv
    		System.out.println(textSearch("Bob", story));
    		
    		// method test		  vvv
    		System.out.println("It works if this prints");
    	}
    	
    	
    }
    I get the console error :

    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 153
    at java.lang.String.substring(Unknown Source)
    at JavaPractice.textSearch(JavaPractice.java:10)
    at JavaPractice.main(JavaPractice.java:49)

    which I am pretty sure means that, in the secondif-then statement, the iterator i can't be grabbed by text.substring() from the counter because at a certain point i, the number of characters in text will be exceeded; i cannot be grabbed because there is no value outside of the text String. I'll try to alter the text for this, but I could use some tips.

    If I'm doing something totally wrong and don't know about it, please tell me! Thank you!
    Last edited by NickB750; 04-08-2016 at 05:37 AM.

  4. #4
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,807
    Rep Power
    12

    Default Re: java problem with for-loop

    Lets say query = "abc" and text = "abcd".

    Your loop continues while i < text.length (which is 4). When i = 3 (which is < 4) what value do you think i + query.length() will have? Will that value be a valid value to substring text?

  5. #5
    Sizzlewump's Avatar
    Sizzlewump is offline Member
    Join Date
    Oct 2010
    Location
    MI, USA
    Posts
    68
    Rep Power
    0

    Default Re: java problem with for-loop

    What happens when you take line 19:
    Java Code:
     i = text.length();
    and put it at line 21? Try putting a couple of print statements in between the if statements to see if and when they execute. It seems that only one of your if statements is triggering for your current variable and story configuration.
    "The secret to getting what you want is to reject everything that you don't want." -Wolbers

  6. #6
    NickB750 is offline Member
    Join Date
    Apr 2016
    Posts
    3
    Rep Power
    0

    Default Re: java problem with for-loop

    Okay, that makes sense. If I get this right, when i = 3, i + query.length will equal 3 + 3 (because "abc".length() is equal to 3), and so it is equal to 6, which is outside of the length of text.

    I figured a way around this: which is by checking instead if(text.substring(i - query.length(), i).equals(query)) and starting the loop at i = query.length() so that the counter stays inside text.length() (and because anything .length() can't be less than zero). Here's the updated code:

    Java Code:
    public class JavaPractice {
         
        static String textSearch(String query, String text) {
            int hit = 0;
            text = text + "!@#$%^&*()";
            // if i gets to the points where there is no more text,
            // the loop can't check if there's a query (there can't be
            // because would be no more text)
            for(int i = query.length(); i < text.length(); i++) {
                if(query.length() > text.length()) {
                	System.out.println();
                        return "";
                } 
                else if(text.substring(i - query.length(), i).equals(query)) {
                    hit += 1;
                }
                
            }
            System.out.println("# of '" + query + "' found: " + hit);
            return "";
        }
         
        public static void main(String[] args) {
            String story = "There was a man named Bob who"
                    + " was fascinated by his name - Bob. "
                    + " He said the name 'Bob' to himself"
                    + " many times a day to emphasize its"
                    + " generic qualities. ";
             
            String puzzle = "111111111111111111111I111111111111111I111111111111111111I1111111111111111111111111I111111111111111111111111111111I1111111111111111111111111"; 
            
            // method call        vvv
            System.out.println(textSearch("Bob", story));
             
            System.out.println(textSearch("I", puzzle));
            
            // method test        vvv
            System.out.println("There is no error in the loop if this prints");
            
            System.out.println(textSearch("This is a pretty big string", "This"));
        }
         
         
    }
    and here is the result in the console :

    # of 'Bob' found: 3

    # of 'I' found: 5

    There is no error in the loop if this prints
    # of 'This is a pretty big string' found: 0


    so no errors, and it works!

    I had to get another conditional to check if query.length() was greater than text.length(), since a search wouldn't work with that.

    Thank you so much for your help! Does this forum have a system where I can give you credit?

Similar Threads

  1. Having a Problem with my Java Program For Statement Loop?
    By William Hagen in forum New To Java
    Replies: 12
    Last Post: 09-08-2015, 10:32 AM
  2. Very Newb to Java with For Loop problem
    By burban in forum New To Java
    Replies: 3
    Last Post: 11-05-2012, 12:06 AM
  3. Replies: 2
    Last Post: 11-07-2011, 02:25 AM
  4. While Loop Problem with Java Assignment Program
    By welsh_rocker in forum New To Java
    Replies: 9
    Last Post: 01-12-2011, 01:55 PM
  5. java loop problem
    By filem_funk in forum New To Java
    Replies: 5
    Last Post: 11-10-2009, 03:56 AM

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
  •