Question

In: Computer Science

Here is an example of jumping out of a loop too early. The code below is...

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");
}
}

Solutions

Expert Solution

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 !!!


Related Solutions

Study the following code with a while-loop and convert it to a for-loop (fill in the...
Study the following code with a while-loop and convert it to a for-loop (fill in the blanks). int i=4, result=1; while(i>1) { result *= i; i--; } The following for-loop performs the same functionality: int result=1; for (__________ i=4; i _________1;____________) { result *= i; }
Skydiving – jumping out of an airplane with a parachute – is incredibly fun, but also...
Skydiving – jumping out of an airplane with a parachute – is incredibly fun, but also dangerous.  The risk of dying in a skydiving accident is actually very small – for this problem, we will assume it is zero. However, there is a substantial risk of other injuries. There are standard precautions a skydive operator can take – such as using more modern equipment, hiring experienced instructors, and taking extra care in packing the parachutes – to reduce this risk.  The cost...
Open Average Test Scores while loop, comment out the while loop and add a for loop...
Open Average Test Scores while loop, comment out the while loop and add a for loop that averages 4 test scores. Code C# While loop code using System; class Program { static void Main() { int count = 0, total = 0, number;    while (count < 3) { Console.Write("Enter a number: "); number = Convert.ToInt32(Console.ReadLine()); total += number; count++; }    double average = total / 3.0; Console.Write("Average = " + average.ToString("####0.00")); } }
CODE WITH ARDUINO: With an RGB Led, Use the iterative loop (for loop) to make red,...
CODE WITH ARDUINO: With an RGB Led, Use the iterative loop (for loop) to make red, blue, and green. Use ‘analogWrite’ command inside the 'for loop.' Use the value ranges from 0-255 for this command. So, to activate any of the pins, the value should be 255. To turn off 0. pattern: First for loop Red light – delay – Second for loop for blue light – delay - Third for loop for green light - delay. (The resulting lights...
Write a python code which prints triangle of stars using a loop ( for loop )...
Write a python code which prints triangle of stars using a loop ( for loop ) Remember what 5 * "*" does The number of lines of output should be determined by the user. For example, if the user enters 3, your output should be: * ** *** If the user enters 6, the output should be: * ** *** **** ***** ****** You do NOT need to check for valid input in this program. You may assume the user...
Loop invariants: Consider the following Python function that merges two sorted lists. Here is a loop...
Loop invariants: Consider the following Python function that merges two sorted lists. Here is a loop invariant for loop 1: “the contents ofnewlistare in sorted order,newlistcontainsaelements oflistAandbelements oflistB” def mergeSortedLists(listA, listB):  newlist = [ ]  a = 0  b = 0  # loop 1  while a < len(listA) and b < len(listB):   if listA[a] < listB[b]:    newlist.append(listA[a])    a +=1   else:    newlist.append(listB[b])    b +=1  if a < len(listA):   newlist.extend(listA[a:])  if b < len(listB):   newlist.extend(listB[b:])  return newlist (a) Write down (in regular...
make a tree for the Chordates – include changes here too
make a tree for the Chordates – include changes here too
The programming language that is being used here is JAVA, below I have my code that...
The programming language that is being used here is JAVA, below I have my code that is supposed to fulfill the TO-DO's of each segment. This code in particular has not passed 3 specific tests. Below the code, the tests that failed will be written in bold with what was expected and what was outputted. Please correct the mistakes that I seem to be making if you can. Thank you kindly. OverView: For this project, you will develop a game...
It is 3pm and you are hungry, but it is too early for dinner so you...
It is 3pm and you are hungry, but it is too early for dinner so you decide to eat a Snickers bar. Since a Snickers has sugar, fat and protein many of the metabolic pathways you have learned about this semester kick into gear. a. Explain (words or diagram or combo of both) how the fat from the candy is processed, starting with absorption in the digestive system and ending with storage in adipose cells. b. Apply the redundancy =...
1. The lines of code below form a counting loop: LoadDelay mov.w #0x001A, R15 LoopTop dec.w...
1. The lines of code below form a counting loop: LoadDelay mov.w #0x001A, R15 LoopTop dec.w R15 jnz LoopTop Done How many times will this loop execute? Provide the answer in decimal_________ 2. Suppose the state of bits at P1OUT are 10110111 and the following line is executed: xor.b #0x05,&P1OUT What is the new state of bits at P1OUT after the above line executes? Provide the answer in binary_____________ 3. What value is contained in R9 after the following lines...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT