Please fix the following java program so that when you run the program and enter
ID: 3696464 • Letter: P
Question
Please fix the following java program so that when you run the program and enter a three letter word, it only outputs the Resultant string ONCE instead of printing it many times.
import java.util.Scanner;
public class FinalQ2
{
public static void main(String args[])
{
String input,result;
Scanner s = new Scanner(System.in);
//input three letter word from user
System.out.println("Enter a three letter word: ");
input = s.next();
//do not accept if word is not of length 3
while(input.length()!=3)
{
System.out.println("The word you entered was not a three letter word. Please enter again: ");
input = s.next();
}
String alphabet="abcdefghijklmnopqrstuvwxyz";//string storing alphabets
int character;
int i=0;
//replace every character of input string with a random letter
while(i {
//generate random index of alphabet string
character=(int)(Math.random()*26);
//if the characters do not match,repace the character
if(alphabet.charAt(character)!=input.charAt(i))
{
result = input.replace(input.charAt(i),alphabet.charAt(character));
input = result;
}
else
{
//while the characters match,keep generating new indexes
while(alphabet.charAt(character)!=input.charAt(i))
{
character=(int)(Math.random()*26);
result = input.replace(input.charAt(i),alphabet.charAt(character));
input = result;
}
i++;
}
System.out.println("Resultant string: "+input);//display result
}
}
}
Explanation / Answer
Hi, I have modified the code. It is working fine as you desired. Highlighted lines are code changes.
FinalQ2.java
import java.util.Scanner;
public class FinalQ2
{
public static void main(String args[])
{
String input,result;
Scanner s = new Scanner(System.in);
//input three letter word from user
System.out.println("Enter a three letter word: ");
input = s.next();
//do not accept if word is not of length 3
while(input.length()!=3)
{
System.out.println("The word you entered was not a three letter word. Please enter again: ");
input = s.next();
}
String alphabet="abcdefghijklmnopqrstuvwxyz";//string storing alphabets
int character;
int i=0;
//replace every character of input string with a random letter
while(i < 3) {
//generate random index of alphabet string
character=(int)(Math.random()*26);
//if the characters do not match,repace the character
if(alphabet.charAt(character)!=input.charAt(i))
{
result = input.replace(input.charAt(i),alphabet.charAt(character));
input = result;
}
else
{
//while the characters match,keep generating new indexes
while(alphabet.charAt(character)!=input.charAt(i))
{
character=(int)(Math.random()*26);
result = input.replace(input.charAt(i),alphabet.charAt(character));
input = result;
}
}
i++;
}
System.out.println("Resultant string: "+input);//display result
}
}
Output:
Enter a three letter word:
fun
Resultant string: byg
---------------------------------------------------------
Enter a three letter word:
abc
Resultant string: pqp