Difference between revisions of "Debugging Practice"

From CompSciWiki
Jump to: navigation, search
Line 2: Line 2:
 
|ProblemName=Debugging Practice
 
|ProblemName=Debugging Practice
  
|Problem=The code provided below was written by a student who challenged to write a program that reversed every word in a provided sentence.  After testing it with a single word, the student was confident that the code would for a full sentence.  Unfortunately, that is not the case.  Find all the bugs in the student's code, and fix them.  Hint: there are three of them.
+
|Problem=The code provided below was written by a student who was challenged to write a program that reversed every word in a provided sentence.  After testing it with a single word, the student was confident that the code would for a full sentence.  Unfortunately, that is not the case.  Find all the bugs in the student's code, and fix them.  Hint: there are three of them.
 
<pre>
 
<pre>
 
import javax.swing.JOptionPane;
 
import javax.swing.JOptionPane;

Revision as of 14:08, 6 April 2010

Back to the Program-A-Day homepage

Problem

The code provided below was written by a student who was challenged to write a program that reversed every word in a provided sentence. After testing it with a single word, the student was confident that the code would for a full sentence. Unfortunately, that is not the case. Find all the bugs in the student's code, and fix them. Hint: there are three of them.

import javax.swing.JOptionPane;

public class WordReversal 
{
    public static void main( String[] args ) 
    {
        int lastSpace = 0;
        int nextSpace = 0;
        String result = "";
        String reversedWord = "";
        String currWord = "";

        String input = JOptionPane.showInputDialog( "Enter a sentence:" );
        while( nextSpace >= 0 ) 
        {
            nextSpace = input.indexOf( ' ', lastSpace );

            if( nextSpace != -1 ) 
            {
                currWord = input.substring( lastSpace, nextSpace + 1 );
            } 
            else 
            {
                currWord = input.substring( lastSpace, input.length() );
            }

            for( int j = currWord.length() - 1; j >= 0; j-- ) 
            {
                reversedWord = reversedWord + currWord.charAt( j );
            }

            result = result + reversedWord;
        }

        JOptionPane.showMessageDialog( null, result, "Reversed Words",
                JOptionPane.INFORMATION_MESSAGE );
    }
}
 

String Methods & Debugging

Wiki array02.jpg

Solution

The solution...

Code

Solution Code

Back to the Program-A-Day homepage