In: Computer Science
Here is an example of jumping out of a loop too early. The code below is intended to test if all of the letters in a string are in ascending order from left to right. But, it doesn’t work correctly. Can you fix it? Fix the code below so it does not leave the loop too early. Try the CodeLens button to see what is going on. When should you return true or false? p
public class Loop3
{
public static boolean isInOrder(String check)
{
int pos = 0;
while (pos < check.length() - 1)
{
String letter1 = check.substring(pos, pos+1);
String letter2 = check.substring(pos+1, pos+2);
if (letter1.compareTo(letter2) < 0)
{
return true;
}
pos++;
}
return false;
}
public static void main(String[] args)
{
System.out.println(isInOrder("abca") + " should return
false");
System.out.println(isInOrder("abc") + " should return true");
}
}
public class Loop3
{
public static boolean isInOrder(String check)
{
int pos = 0, count = 0;
while (pos < check.length() - 1)
{
String letter1 = check.substring(pos, pos + 1);
String letter2 = check.substring(pos + 1, pos + 2);
if (letter1.compareTo(letter2) < 0)
{
count += 1;
}
pos++;
}
if (count == (check.length() - 1))
{
return true;
}
else
{
return false;
}
}
public static void main(String[] args)
{
System.out.println(isInOrder("abca") + " should return false");
System.out.println(isInOrder("abc") + " should return true");
}
}
Output:
Thumbs Up Please !!!