Understanding / reading a for loop searching through a string

  • (2 Pages)
  • +
  • 1
  • 2

26 Replies - 1131 Views - Last Post: 20 January 2014 - 07:47 PM Rate Topic: -----

#1 KnifeTea  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 21-November 13

Understanding / reading a for loop searching through a string

Posted 19 January 2014 - 05:46 PM

I'm struggling to join where this is going :

public class Woirnver {

	public static void main(String[] args) {

		// self explanatory
		String lookThrough = "This is going away";

		// self ex.
		String subString = "away";

		// Initialise boolean variable and alter the default value. If the
		// boolean is left on default it will register as true on line 32 and
		// although work the program will not run correctly.
		boolean foundIt = true;

		// This establishes the remaining amount of characters after the
		// substring has been subtracted from lookThrough. Not sure why this is
		// necessary.
		int max = lookThrough.length() - subString.length();

		// I can't follow this loop through.
		test: for (int i = 0; i <= max; i++) {
			int n = subString.length();

			// because we can't use the same variable twice within the same
			// balanced braces.
			int j = i;
			int k = 0;
			while (n-- != 0) {
				// I don't really follow where j++ and k++ would be in relation
				// to lookThrough. They are both iterating through the text at
				// the same rate aren't they? I've a feeling that 'max'comes
				// into play - and that perhaps i / j are 5 characters behind /
				// ahead k, but I can't really work out how or why this matters.
				// If this is right and j is terminated at the value of i then
				// it would stop searching through the text once it got to the
				// white space after going? I don't see how that would return the word. 
				//I'm not really sure where else to go from here! 
				if (lookThrough.charAt(j++) != subString.charAt(k++)) {

					continue test;
				}
			}

			foundIt = true;
			break test;
		}

		System.out.println(foundIt ? "Found it " : "Didn't find it");
		System.out.println(max);
		System.out.println(lookThrough.length());

	}
}











I've annotated bit's, but it's line 30 (or line 22 I guess) that I'm struggling to follow through a bit...

The for loop is searching through the String lookThrough and matching the character at the position j (which has the value of i, which is 14) against the character returned by k, which I'm presuming is 18 as it's not got anything subtracted from it, although I don't see how It would get there seeing as the loop terminates at 14... Or does it?

I don't really get why the loop would return different values from j and k...

There's clearly a fair chunk that I'm missing on this though, hope what I've said makes sense ://>

Is This A Good Question/Topic? 0
  • +

Replies To: Understanding / reading a for loop searching through a string

#2 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: Understanding / reading a for loop searching through a string

Posted 19 January 2014 - 05:59 PM

Because k is initialised inside the loop, it will reset to 0 every loop iteration.

Edit (clarity): the same goes for j, except it is "reset" to i, which is incrementing correctly.

This post has been edited by Flukeshot: 19 January 2014 - 06:00 PM

Was This Post Helpful? 1
  • +
  • -

#3 KnifeTea  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 21-November 13

Re: Understanding / reading a for loop searching through a string

Posted 19 January 2014 - 06:06 PM

Ah OK, I didn't realise that! But - so is j?

But also n--, does that mean that the loop will in fact only run 4 times?
Was This Post Helpful? 0
  • +
  • -

#4 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: Understanding / reading a for loop searching through a string

Posted 19 January 2014 - 06:13 PM

For j's effect, see my previous post. As for n, this current version of the program will search through the string 4 times for every iteration of i.
Was This Post Helpful? 0
  • +
  • -

#5 KnifeTea  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 21-November 13

Re: Understanding / reading a for loop searching through a string

Posted 19 January 2014 - 06:27 PM

So it searches 4 characters deep every time it runs?

the first search would be "This"

second "his "

Third "is i"

etc....

I thought that it could only search for one character at a time for some reason, not sure where I got that idea from....

So once it get's to 14 (which would be the first letter of away...) It counts 4 in, 'a' 'w' 'a' 'y' and the program alters foundIt to true, and continues to line 49.
Was This Post Helpful? 0
  • +
  • -

#6 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: Understanding / reading a for loop searching through a string

Posted 20 January 2014 - 01:57 PM

No it searches 12 times every time it runs. :)

It will run the while(n-- =! 0) for every iteration of i.

So, if i iterates 4 times "this".length();, there will be a while loop running 3 times --n is --"this".length(); which is 3. (And becomes 2, then 1, then the loop will not run).

It's a bit complex to explain but I hope that helps.
Was This Post Helpful? 0
  • +
  • -

#7 KnifeTea  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 21-November 13

Re: Understanding / reading a for loop searching through a string

Posted 20 January 2014 - 02:32 PM

Right, well, hmm... I have no idea where I'm meant to grab onto this!

I'm going to do it in bits

Quote

It will run the while(n-- =! 0) for every iteration of i


So every time i increments, the while loop is run. So the while loop is run separately, up to 14 times. Each time the while loop runs, it searches through 4 characters at a time?

I don't really get what I just said, I thought that it would have to search for 1 character at a time. But apparently it's 4.

and it's n-- not --n...

Quote

--n is --"this".length();
that would make it 4 wouldn't it?

:/

Cheers.

This post has been edited by andrewsw: 20 January 2014 - 02:42 PM
Reason for edit:: Removed previous quote

Was This Post Helpful? 0
  • +
  • -

#8 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: Understanding / reading a for loop searching through a string

Posted 20 January 2014 - 03:51 PM

Oh so it is :) that still makes it run 16 times.
Was This Post Helpful? 0
  • +
  • -

#9 KnifeTea  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 21-November 13

Re: Understanding / reading a for loop searching through a string

Posted 20 January 2014 - 03:55 PM

View PostFlukeshot, on 20 January 2014 - 03:51 PM, said:

Oh so it is :)/> that still makes it run 16 times.


so which bit runs 16 times? the while? And each time the while runs it searches through 4 characters?

when I said

Quote

the first search would be "This"

second "his "

Third "is i"

etc....


That was wrong, but what is actually happening?
Was This Post Helpful? 0
  • +
  • -

#10 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: Understanding / reading a for loop searching through a string

Posted 20 January 2014 - 04:35 PM

I guess it's been unintentional, but you have made a nested loop.

for i (0 to 3)
   while n-- != 0 (4 to 1)



The result being:

i = 0 -> while 4, 3, 2, 1
i = 1 -> while 4, 3, 2, 1
i = 2 -> while 4, 3, 2, 1
i = 3 -> while 4, 3, 2, 1

for a total of 16 iterations of the while loop
Was This Post Helpful? 0
  • +
  • -

#11 KnifeTea  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 21-November 13

Re: Understanding / reading a for loop searching through a string

Posted 20 January 2014 - 04:50 PM

View PostFlukeshot, on 20 January 2014 - 04:35 PM, said:

I guess it's been unintentional, but you have made a nested loop.

for i (0 to 3)
   while n-- != 0 (4 to 1)



The result being:

i = 0 -> while 4, 3, 2, 1
i = 1 -> while 4, 3, 2, 1
i = 2 -> while 4, 3, 2, 1
i = 3 -> while 4, 3, 2, 1

for a total of 16 iterations of the while loop


Yeah, it's what was in the program tutorial. (It's off the Oracle page... I should have mentioned)

OK, so for every increment of i the while loop checks 4 characters (subText.length) against 4 characters of the main string (lookThrough)

Isn't that what I said in post #5?

I don't really see where the

Quote

there will be a while loop running 3 times --n is --"this".length(); which is 3. (And becomes 2, then 1, then the loop will not run).
come's into it as once it'd got to i = 16 -> while 4, 3, 2, 1 there'd be no point going back and doing i = 0 -> while 3, 2, 1 but then i guess the loop would have been cut off / ended by then anyway because i would have reached max

And I don't really see how the while statement get's chance to go 4, 3, 2, 1 when the if statement (lookThrough.charAt(j++) != subString.charAt(k++)) sends the program back to test as soon as a non matching value is hit?

I think I may have gone full retard
Was This Post Helpful? 0
  • +
  • -

#12 andrewsw  Icon User is online

  • the case is sol-ved
  • member icon

Reputation: 6380
  • View blog
  • Posts: 25,775
  • Joined: 12-December 12

Re: Understanding / reading a for loop searching through a string

Posted 20 January 2014 - 05:26 PM

I recommend that you never embed increment/decrement operators (++/--) within an expression. Their behaviour is hard to predict and will bite you.
Was This Post Helpful? 2
  • +
  • -

#13 KnifeTea  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 21-November 13

Re: Understanding / reading a for loop searching through a string

Posted 20 January 2014 - 05:37 PM

View Postandrewsw, on 20 January 2014 - 05:26 PM, said:

I recommend that you never embed increment/decrement operators (++/--) within an expression. Their behaviour is hard to predict and will bite you.


Don't think I will after this ;)

Would like to thank who ever at Oracle stuck this into the tutorials... and at like lesson three or something.

Would like to know how it works though!
Was This Post Helpful? 0
  • +
  • -

#14 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: Understanding / reading a for loop searching through a string

Posted 20 January 2014 - 05:41 PM

Yeah, I had a brainfart over --n and n--, and overlooked a few elements of the program, sorry. :sweatdrop:

Let's step through the program a line at a time (you can do this in debug mode if you want to follow along) and get to the bottom of it.

public class Woirnver {
	public static void main(String[] args) {
		String lookThrough = "This is going away";
		String subString = "away";

		boolean foundIt = true;

		int max = lookThrough.length() - subString.length(); //int max = 18 - 4 (14)

		test: for (int i = 0; i <= max; i++) { //for 0-14 (15 iterations)
			int n = subString.length(); //n = 4

			int j = i; //j becomes set to whatever i is
			int k = 0; // k resets to 0
			while (n-- != 0) { //loop 4 times (each iteration decrements n until it is 0)
				if (lookThrough.charAt(j++) != subString.charAt(k++)) { 
					continue test;
				}
			} // let's cut here



(first loop) i=0, j=0, k=0 -> if 'T' != 'a' then continue, it's not, so we continue and increment i
(second loop) i=1, j=1, k=0 -> if 'h' != 'a' then continue, it's not, so we continue and increment i
... continue this until we actually get a match and see what happens ...
(15th loop) i=15, j=15, k=0 -> if 'a' != 'a' then continue, it is equal, so we ignore the continue and decrement n
(15th loop 2nd nest) i=15, j=16, k=1 -> if 'w' != 'w' then continue, it is equal so we ignore the continue and decrement n
... see where this is going? ...
//we finally exit the loop.
//If we successfully made it past the while loop without hitting continue, we will set foundIt to true.
			foundIt = true;
			break test; //and exit the loop entirely
		}

		System.out.println(foundIt ? "Found it " : "Didn't find it"); //now we test if the boolean was set to true
		System.out.println(max); // we print max (14)
		System.out.println(lookThrough.length()); // and the length of the whole string (18)

	}
}


So, as far as I can tell, there actually wasn't anything wrong with this code. Maybe I went full retard? :)

Anyway, I hope this helps you understand it, finally! (It helped me :P)

This post has been edited by Flukeshot: 20 January 2014 - 05:43 PM

Was This Post Helpful? 0
  • +
  • -

#15 andrewsw  Icon User is online

  • the case is sol-ved
  • member icon

Reputation: 6380
  • View blog
  • Posts: 25,775
  • Joined: 12-December 12

Re: Understanding / reading a for loop searching through a string

Posted 20 January 2014 - 05:43 PM

@OP You could rewrite the code without the embedded inc/dec operators. However, if it has become an annoyance, then I would just move on.

This post has been edited by andrewsw: 20 January 2014 - 05:46 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2