For loops are such a fundamental part of programming in any language and I have been grappling with the intricacies of nested for loops in Java.
Let's say the problem is to report whether there are repeated letters in a string input by the user without using an array.
A nested for loop is perfect for solving this problem but it is not as easy as it first appears.
The loops should work as follows:
The inner loop cycles through the string and compares them to the letter in the outer loop continuing to do so until a repeat is found or no repeat is found and an appropriate message displayed. The crucial issue is getting the inner loop to start off at the 2nd letter in the string so as the two loops are not comparing the same letter!
Initially I tried something like;
char i;
for(i = userString.charAt(0); i <= userString.length(); i++) char j; for(j = userString.charAt(1); j <= userString.length(); j++) But the loops did not seem to work with userString.charAt() as a starting point? Unsure why! so I went back to the standard:
for (i = 0; i <= userString.length()-1; i++){
int j, count;
count = 0;
for(j = 0; j <=userString.length(); j++){ if( userString.charAt(i) == userStringcharAt(j))
hoping that i <= userString.length()-1 and j <= userString.length(); might do the trick. Nada! Anyway it transpires that the solution was very simple and I had just not thought to do it. j = i + 1!
for (i = 0; i <= userString.length()-1; i++) { int j, count; count = 0;
for(j = i+1; j <> {
I am still unsure:
- Why j <>
- Why there is still a need to use i <= userString.length()-1 rather than
i <= userString.length().
Your first attempt didn't work because you were trying to increment a char. Those don't increment nicely, and if they do at all, it would be going from a to b to c, not following your string...
ReplyDeleteAs for why your outer loop has to end at userString.length()-1 instead of userString.length(), remember that your inner loop starts looking at the next char after the one your outer loop is currently on. So if your outer loop goes all the way to the last char, your inner loop on the last round would start looking at the char after the last one, which gets messy...
One other catch you might want to look out for: How do you handle when a char is duplicated more than once? (more than 2 of it in the string) Do you want to count it again or have some way to ignore the duplicated detections of duplication?
IE: "AAAA"
First outer loop it detects 3 more 'A's after the first. Second outer iteration: Do you want it to detect the last two 'A's again or ignore them after the first?
(This is a somewhat larger pain in the ass, which requires keeping some kind of table of char's you've already seen...)