WAP in BlueJ to accept a word in lower case and display the new word after removing all the repeated letters.
Sample Input: apple
Sample Output: aple
Answers
Remove Duplicate Letters - Java
We first take user input of the word with a Scanner object. Even though the problem statement asks the user to input a lowercase word, we convert the input word to lowercase anyway, using the method.
After that, we initialize a new variable, newWord, as an empty string. We start looping through the characters of the original word.
If the character is found in the newWord, we skip it, else we add it to the newWord.
Finally, we just have to print out the new word.
The Code
import java.util.Scanner;
public class RemoveRepeatedLetters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// Take user input
System.out.print("Enter a word: ");
// Convert the input word to lower case
String word = in.next().toLowerCase();
// Close the Scanner object
in.close();
// Initialize a new word with empty string
String newWord = "";
// Loop through the word
for (int i = 0; i < word.length(); i++) {
// Extract character at i-th position
char letter = word.charAt(i);
// If letter not found in newWord, add it to newWord
// Thus, repeated letter are skipped
if (newWord.indexOf(letter) < 0) {
newWord += letter;
}
}
// Print out the newWord without repeated letters
System.out.println(newWord);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word in lower case: ");
String word = sc.nextLine(); // Accepts the input word from the user
String newWord = ""; // Initialize an empty string to store the new word
for (int i = 0; i < word.length(); i++) { // Iterate through each character in the input word
char c = word.charAt(i);
if (newWord.indexOf(c) == -1) { // If the character is not found in the new word
newWord += c; // Append the character to the new word
}
}
System.out.println("The new word after removing all repeated letters is: " + newWord);
}
}
❖ In this code, we first import the Scanner class, which allows us to read input from the user. We then create an instance of the Scanner class, sc, which we will use to read the input word from the user.
❖ We prompt the user to enter a word in lower case, and we use the nextLine() method to read the input into the word variable.
❖ Next, we initialize an empty string, newWord, which will store the new word after removing all the repeated letters.
❖ In the for loop, we iterate through each character in the word and use the indexOf() method to check if the current character is present in the newWord. If the indexOf() method returns -1, it means that the character is not present in the newWord, and we can safely append it to the end of the newWord.
❖ Finally, we display the newWord after removing all the repeated letters.