In: Computer Science
The files provided in the code editor to the right contain syntax and/or logic errors. In each case, determine and fix the problem, remove all syntax and coding errors, and run the program to ensure it works properly.
Please Fix code and make Copy/Paste avaliable
// Application allows user to enter a series of words
// and displays them in reverse order
import java.util.*;
public class DebugEight4
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int x = 0, y = 0;
String array[] = new String[100];
String entry;
final String STOP = "STOP";
StringBuffer message = new StringBuffer("The words in reverse order are\n");
System.out.println("Enter any word\n" +
"Enter + STOP + when you want to stop");
entry = input.next();
while(!(entry.equals(STOP)))
{
array[x] = entry;
++x;
System.out.println("Enter another word\n" +
"Enter " + STOP + " when you want to stop");
entry = input.next();
}
for(y = x - 1; y > 0; ++y)
{
message.append(array[y]);
message.append("\n");
}
System.out.println(message);
}
}
Explanation:
Two logical errors were there in the for loop, written at the last.
1) y should start from x-1 and keep decrementing by 1 every time, it was getting incrementing instead.
2) In the condition of the for loop, index 0 should also be covered, so, y>=0 is the right condition
Correct code:
import java.util.*;
public class DebugEight4
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int x = 0, y = 0;
String array[] = new String[100];
String entry;
final String STOP = "STOP";
StringBuffer message = new StringBuffer("The words in reverse order are\n");
System.out.println("Enter any word\n" +
"Enter + STOP + when you want to stop");
entry = input.next();
while(!(entry.equals(STOP)))
{
array[x] = entry;
++x;
System.out.println("Enter another word\n" +
"Enter " + STOP + " when you want to stop");
entry = input.next();
}
for(y = x - 1; y >= 0; --y)
{
message.append(array[y]);
message.append("\n");
}
System.out.println(message);
}
}
Output:
PLEASE UPVOTE IF YOU FOUND THIS HELPFUL!
PLEASE COMMENT IF YOU NEED ANY HELP!