Difference between revisions of "Debugging Practice"
From CompSciWiki
Line 4: | Line 4: | ||
|Problem=Find the bugs in the code provided below. Hint: there are lots | |Problem=Find the bugs in the code provided below. Hint: there are lots | ||
<pre> | <pre> | ||
− | + | 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); | ||
− | + | for (int j = 0; j < currWord.length(); j++) | |
− | + | { | |
− | + | reversedWord = reversedWord + currWord.charAt(j); | |
− | + | } | |
+ | } | ||
− | + | result = result + reversedWord; | |
+ | } | ||
+ | |||
+ | JOptionPane.showMessageDialog( null, result, "Reversed Words", JOptionPane.INFORMATION_MESSAGE ); | ||
+ | } | ||
} | } | ||
</pre> | </pre> |
Revision as of 11:48, 6 April 2010
Back to the Program-A-Day homepage
ProblemFind the bugs in the code provided below. Hint: there are lots 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); for (int j = 0; j < currWord.length(); j++) { reversedWord = reversedWord + currWord.charAt(j); } } result = result + reversedWord; } JOptionPane.showMessageDialog( null, result, "Reversed Words", JOptionPane.INFORMATION_MESSAGE ); } } |
SideSectionTitle
An image or By Students section | |
---|---|---|
SolutionThe solution... | ||
CodeSolutionCode goes here. Please DO NOT put your code in <pre> tags! |