Jordan Lee Burnes Jordan Lee Burnes - 2 months ago 9
Java Question

Printing UI Without Vowels Using Loops Without replaceAll(); in Java

I am trying to take user input and modify it so that I print the string without any vowels. I have been able to do this successfully with the following code.

Scanner in = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = in.next();

String newString = word.replaceAll("[aeiouAEIOU]","1");
System.out.printf("%s", newString);


However, I am trying to get the same effect by using a loop without the above method, replaceAll(). I have tried one other time, but got mixed up in the logic and restarted. My latest attempt is below and I cannot understand why it will not run properly. I will enter a string and without any error message it will not print back anything. The only time I get it to work is when I give it single characters to find in the string using something like

if(letter.contains("a"))


If the condition is found true it will print back a string of a's, however, this does not work for any combination of characters, only single ones. My complete code is below.

import java.util.Scanner;

public class practice
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = in.next();
int i = 0;

while (i < word.length()){
String letter = word.substring(i, (i+1));
if(letter.contains("[bcdfghjklmnpqrstvwxyz]")){
System.out.printf("%s",letter);
}
i++;
}
}
}


I am simply trying to find a way to complete this program only using conditionals, loops, UI, and only the methods length(), contains() or indexOf(), charAt(), and substring(x,y). Thanks in advance for any help I hope I have provided enough information.

Here is some sample output:

Enter a word:
Jordan


After I entered the word the program stops.

Answer

One way would be to convert your string to an array of characters toCharArray() and then compared with a case and add a new chain StringBuilder

 String word = in.next();
     StringBuilder bul = new StringBuilder();
     for (char arg : word.toLowerCase().toCharArray()) {
         switch(arg)
         {
             case 'a': System.out.println("A");break;
             case 'e': System.out.println("E");break;
             case 'i': System.out.println("I");break;
             case 'o': System.out.println("O");break;
             case 'u': System.out.println("U");break;
             default:
                 bul.append(arg);
         }
     }
     System.out.println(bul); //String not Vowels

in your code might change why a selected character with subtring can never contain such a long string like that "[bcdfghjklmnpqrstvwxyz]"

if(letter.contains("[bcdfghjklmnpqrstvwxyz]")){...}

for

if("[bcdfghjklmnpqrstvwxyz]".contains(letter.toLowerCase())){...}
Comments