What is a beginner friendly way to write this for loop?
for(char i=tokens[1].charAt(0); i != tokens[2].charAt(0); i = (char)((tokens[1].charAt(0) > tokens[2].charAt(0))? i-1 : i+1)) {
...
}
Here, to get the first letter of a string, you must use the charAt(0). So, it is to be there in modified code also. What you can reduce is the increment/ decrement operation performed and you can move it at the end of the for loop code you have written. This leaves no change, you can write in the both ways. If you want to make for loop looking small, you can even take the initialization of i outside the loop. This is working similar as while loop if you are taking both 1 and 3 from for(1,2,3). So, to minimize this code and make it understandable, I moved the increment/decrement after the for loop implementation.
Code:
char i;
for(i = tokens[1].charAt(0); i!=tokens[2].charAt(0); )
{
//your execution code of the for loop
if(tokens[1].compareTo(tokens[2]) > 0)
{
i = (char)(i-1);
}
else
{
i = (char)(i + 1);
}
}
You can define the variable i just before the for loop, its initialization and condition checking is the same. I removed the third part from the loop and wrote it inside.
Here, the code was comparing both the strings tokens[1] and tokens[2]'s first character. If the tokens[1] is having greater character ( a<b<c..... such) then you need to decrement i or else increment it by 1 and convert it into char again. This was done using conditional operators, I changed it to simple if else condition.
Moreover, you can directly find the difference between the first two characters of the string when their first character are not same using compareTo() method of String class. So, instead of writing
i = (char)((tokens[1].charAt(0) > tokens[2].charAt(0))? i-1 : i+1)
you can write the if-else to make it simplified.
Do comment if there is any query. Thank you. :)
Get Answers For Free
Most questions answered within 1 hours.