Removing vowels from an input string using a loop - java

I need my output to only be 5 characters long NOT counting the removed vowels. Currently my code is counting the input length and returning that number minus the vowels. This might be confusing. If I input "idontthinkso" it only returns "dnt" instead of what I want it to print out which is "dntth". Btw, I'm not allowed to use Stringbuilder or anything like that, only a loop, so forgive the code. How can I fix this? Here is my code:
import java.util.Scanner;
public class TweetCompressor {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "";
System.out.println("Type a tweet: ");
String input = keyboard.nextLine();
int f = 0;
int tweetLengthAllowed = 5;
for (int i = 0; i < tweetLengthAllowed; i++) {
char c = input.charAt(i);
if (c == 'a' ||
c == 'e' ||
c == 'i' ||
c == 'o' ||
c == 'u' ||
c == 'A' ||
c == 'E' ||
c == 'I' ||
c == 'O' ||
c == 'U') {
f = 1;
} else {
s = s += c;
f = 0;
}
}
System.out.println(s);
}
}

I'm very much in favor of using a while loop for this, but since you stated you can only use a for loop...
The problem is that your loop will iterate until i = 5, even if a vowel is detected. We need a way to tell the loop to pretend that never happened. You can't decrement i, or you'll be stuck at the same character forever.
Here's what I came up with, I decided to simply increment the tweetLengthAllowed to negate the i increment.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "";
System.out.println("Type a tweet: ");
String input = keyboard.nextLine();
int f = 0;
int tweetLengthAllowed = 5;
for(int i = 0; i < tweetLengthAllowed; ++i) { //Must be a for loop
char c = input.charAt(i);
if(c == 'a'|| c == 'e'|| c == 'i'|| c == 'o'|| c =='u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
f = 1;
tweetLengthAllowed++; //Allows the loop to continue for one more interation
} //end if
else{
s = s += c;
f = 0;
}//end else
} //end for
System.out.println(s);
} //end main
} //end class
Also, if you're going to use a big chain of ORs, please do yourself a favor and make it more readable as I did above.

You can do this simpler. Here I iterate every char in the input and break if it reaches the limit:
import java.util.Scanner;
public class TweetCompressor {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "";
System.out.println("Type a tweet: ");
String input = keyboard.nextLine();
int tweetLengthAllowed = 5;
int i = 0;
boolean isNotVowel;
boolean limitReached;
for (char c : input.toCharArray()) {
isNotVowel = "AEIOUaeiou".indexOf(c) == -1;
limitReached = tweetLengthAllowed <= i;
if (limitReached) { // exit the loop
break;
} else if (isNotVowel) { // append the char
s += c;
i++;
}
}
System.out.println(s);
}
}
Run output:
Type a tweet:
idontthinkso
dntth

Here is my way of doing it:-
import java.util.Scanner;
import java.lang.StringBuffer;
public class Program {
private static String RemoveVowel(String text)
{
int len = text.length();
char[]vowels = {'a','e','i','o','u','A','E','I','O','U'};
StringBuffer sb = new StringBuffer(text);
for(int i = 0;i<len;i++)
{
for(char v : vowels)
{
if(v == text.charAt(i))
{
sb.setCharAt(i,'\0');
}
}
}
return sb.toString();
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter some text to remove vowels from it: ");
String val = scan.nextLine();
System.out.println(RemoveVowel(val));
}
}
I have used string buffer to make the string modifiable and a "for" loop iterates through the length of the string, and one iterates through the "vowels" array; an "if" statement checks if the current character is equal to one of the vowels and if true, it sets the current character to null, which removes the vowel.

public class RemoveVowels {
public static void main(String[] args) {
String inputString = "Java - Object Oriented Programming Language";
System.out.println(inputString.replaceAll("[aeiouAEIOU]", " "));
}
}
Output:
J v - bj ct r nt d Pr gr mm ng L ng g

Related

I am trying to make a program to find consonants, vowels and non-alphabet in a string entered by a user

import java.util.Scanner;
public class Chupapi{
static Scanner input = new Scanner(System.in);
public static void main(String[] args){
String str = " ";
int consonant = 0, vowel = 0, non_alpha = 0;
System.out.print("Enter string: ");
str = input.nextLine();
consonant = getConsonantCount(str);
vowel = getVowelCount(str);
non_alpha = getNonAlphaCount(str);
}
}
Here is my code, am I doing it in the right way? I'm kinda stuck on what I would use to countdown the consonants, vowels, and non-alphabet.
So basically you need to run a for loop and check whether the current char is a vowel or a consonant or a non-alphabet character.
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String str = sc.next();
StringBuffer cosonantSb = new StringBuffer();
StringBuffer vowelSb = new StringBuffer();
StringBuffer noAlphabetSb = new StringBuffer();
for(int idx = 0 ; idx < str.length() ;idx++) {
char currentChar = str.charAt(idx);
if( Character.toUpperCase(currentChar) == 'A' ||
Character.toUpperCase(currentChar) =='E' ||
Character.toUpperCase(currentChar) == 'O' ||
Character.toUpperCase(currentChar) == 'I' ||
Character.toUpperCase(currentChar) == 'U' ) {
vowelSb.append(currentChar);
}
else if(Character.toUpperCase(currentChar) >= 'A' &&
Character.toUpperCase(currentChar) <= 'Z') {
cosonantSb.append(currentChar);
}
else {
noAlphabetSb.append(currentChar);
}
}
System.out.println("Consonants :"+cosonantSb);
System.out.println("Vowels :"+vowelSb);
System.out.println("Non Aplhabets : "+noAlphabetSb);
}
Output:
scbalcb1232434knclnsd]12
Consonants :scblcbknclnsd
Vowels :a
Non Aplhabets : 1232434]12

How do you use charAt with an array?

i am having a bit of trouble in implementing charAt with an array. I am a beginner in Java (and this is my only coding experience i suppose).
The objective: To create a program that the user inputs any string, and the total number of vowels are recorded in the output (case sensitive)
example:
Input: charActer
Output:
a = 1
A = 1
e = 1
import java.util.Scanner;
public class HW5 {
public static void main(String[] args) {
String [] alphabets =
{"aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"};
String vowels = "aAeEiIoOuU";
int found = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: ");
String inputStr = sc.nextLine();
for(int i=0;i<alphabets.length;i++)
{
if(alphabets.charAt[i] == vowels)
*Note: Program is not complete.
You need to check each character of inputStr (dunno what alphabets is about in your code) and see if it can be found in the vowels string.
String vowels = "aAeEiIoOuU";
int found = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: ");
String inputStr = sc.nextLine();
for (int i = 0; i < inputStr.length(); i++) {
if (vowels.indexOf(inputStr.charAt(i)) >= 0) {
found += 1;
}
}
The documentation is helpful if you're having trouble understanding a method or class.
Having said that, there are lots of ways to count vowels in a String.
Your output indicates that you need the counts per vowel per case, and not just the count of all vowels. To do this you will need a map in order to keep track.
Consider something like
String input = "A string with vowels in it";
Map<Character, Integer> counts = new HashMap<≥();
for (int i = 0; i < input.length; i++) {
char c = input.chart(i);
if (c == 'a') {
int tmp = counts.getOrDefault('a', 0);
tmp++;
counts.put('a', tmp);
} else if (c == 'A') {
// same logic as above for uppercase A
} // other else if statements for e, E, i, I, o, O, u, U
}
// the map has all counts per vowel / case
After the map has all counts you can iterate its entry set to print the output you need
for (Map.Entry<Character, Integer> e : counts. entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
If you only need the number of values without breaking it down into which vowels, consider something like (not tested)
String vowels = "AaEeIiOoUu";
String input = "Hello World!";
int numVowels = 0;
for (int i = 0; i < input.length; i++) {
char c = input.charAt(i);
if (vowels.indexOf(c) >= 0) {
numVowels++;
}
}
// do something with numVowels
--
Break the problem into simple steps
Define the vowels to look for
Initialize your counter variable (numVowels)
Loop through the input string and check each character against the ones defined in 1 (vowels).
For each vowel you find, increment your counter variable.
public class Vowels {
public static void main(String[] args) {
Map<Character, Integer> vowels = new HashMap<>();
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: "); //"charActer";
String str = sc.nextLine();
for (int i = 0; i < str.length(); i++) {
Character c = str.charAt(i);
if (c == 'a'
|| c == 'A'
|| c == 'e'
|| c == 'E'
|| c == 'i'
|| c == 'I'
|| c == 'o'
|| c == 'O'
|| c == 'u'
|| c == 'U') {
if (vowels.containsKey(c)) {
vowels.put(c, vowels.get(c) + 1);
} else {
vowels.put(c, 1);
}
}
}
for (Map.Entry<Character, Integer> entry : vowels.entrySet()) {
System.out.print(entry.getKey() + "=" + entry.getValue() + " ");
}
}}
Input : charActer
Output : a=1 A=1 e=1

Write method countVowels to take a string and return the amount of vowels

public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input the string: ");
String str = in.nextLine();
System.out.print("Number of Vowels in the string: " + countVowels(str)+"\n");
}
public String countVowels(String count) {
}
sorry but im very new to java and coding and trying to find a way to create a vowel counter but I seem to struggle with creating one ive tried looking up many answers but cant find one.
Try something like this:
public int countVowels(String str)
{
int vowelCount = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.toLowerCase().toCharArray()[i] == 'a' | str.toLowerCase().toCharArray()[i] == 'e' | str.toLowerCase().toCharArray()[i] == 'i' | str.toLowerCase().toCharArray()[i] == 'o' | str.toLowerCase().toCharArray()[i] == 'u')
{
vowelCount++;
}
}
return vowelCount;
}
and if you want to include 'y', just add another comparison to the if statement
public static String countVowels(String count) {
int Vowelcount = 0;
String[] arr = count.split(" ");
//looping through string array
for (int i = 0; i <= arr.length - 1; i++) {
//looping through each character in the next element
for (char ch : arr[i].toCharArray()) {
//checking if ch == to vowels
if (ch == 'e' || ch == 'a' || ch == 'o' || ch == 'u' || ch == 'i') {
//add counts number of vowels for every string array index
Vowelcount += 1;
}
}
}
return Integer.toString(Vowelcount);
}
This should work just fine... I've split your words in the input string into a string array.

How to convert user input string to pig latin?

Im trying to convert a user entered string that starts with a consonant to pig latin buy moving all the consonants to the end of the word till the word starts with a vowel, and then adding "ay" to the end of the word. I have a for loop that's supposed to do this, but for some reason, it outputs nothing. What am i doing wrong here? Im stumped.
Here's the code:
import java.util.Scanner;
public class two {
public static void main(String[] args) {
System.out.println("Please enter a word");
Scanner word = new Scanner(System.in);
String pigLatin = word.nextLine();
while (!pigLatin.equalsIgnoreCase("quit")) {
if (isVowel(pigLatin.charAt(0))) {
pigLatin = (pigLatin + "way");
System.out.println(pigLatin);
}
else {
for (int i = 0; i < pigLatin.length(); i++) {
char firstChar = pigLatin.charAt(0);
pigLatin = pigLatin.substring(1);
pigLatin = pigLatin + firstChar;
if (i >= pigLatin.length())
{
pigLatin = pigLatin + "ay";
System.out.println(pigLatin);
}
}
}
System.out.println("Please enter a word");
pigLatin = word.nextLine();
}
word.close();
}
private static boolean isVowel(char ch) {
char v = Character.toLowerCase(ch);
if (v == 'a' || v == 'e' || v == 'i' || v == 'o' || v == 'u') {
return true;
}
else {
return false;
}
}
}
You need a less than or equal <= on the i otherwise i is never greater than or equal to pigLatin.length().
for (int i = 0; i <= pigLatin.length(); i++) {
char firstChar = pigLatin.charAt(0);
pigLatin = pigLatin.substring(1);
pigLatin = pigLatin + firstChar;
if (i >= pigLatin.length())
{
System.out.println(pigLatin);
}
}
your for loop condition is
i < pigLatin.length()
and you said in if
if(i >= pigLatin.length()){....}
so this condition will never be true , for that reason there is no output,
see below code ,
import java.util.Scanner;
/**
*
* #author rahmat waisi
*/
public class PigLatin {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
// System.out.print("Please enter a word: , Enter [ quit ] for exit : ");
String pigLatin = scanner.nextLine();
if (pigLatin.equals("quit")) {
break;
}
if (isVowel(pigLatin.charAt(0))) {
pigLatin += "ay";
System.out.println(pigLatin);
} else {
String output = "";
int separation_index = findFirstVowel(pigLatin);
if (separation_index ==-1) {
System.out.println(pigLatin+"ay");
continue;
}
output+= pigLatin.substring(separation_index);
output+= pigLatin.substring(0, separation_index) + "ay";
System.out.println(output);
}
}
}
}
private static boolean isVowel(char ch) {
char v = Character.toLowerCase(ch);
return v == 'a' || v == 'e' || v == 'i' || v == 'o' || v == 'u';
}
private static int findFirstVowel(String str) {
for (int i = 0; i < str.length(); i++) {
if (isVowel(str.charAt(i))) {
return i;
}
}
return -1;
}
}
here is some input:
pig
banana
trash
happy
duck
glove
eat
omelet
are
ffff
quit
and their output is:
igpay
ananabay
ashtray
appyhay
uckday
oveglay
eatay
omeletay
areay
ffffay

How to check if a character in a string is a digit or letter

I have the user entering a single character into the program and it is stored as a string. I would like to know how I could check to see if the character that was entered is a letter or a digit. I have an if statement, so if its a letter its prints that it's a letter, and the same for a digit. The code I have so far doesn't work but I feel like I'm close. Any help you can offer is appreciated.
System.out.println("Please enter a single character: ");
String character = in.next();
System.out.println(character);
if (character.isLetter()){
System.out.println("The character entered is a letter.");
}
else (character.isDigit()){
Syste.out.println("The character entered is a digit.");
You could use:
if (Character.isLetter(character.charAt(0))){
....
You could use the existing methods from the Character class. Take a look at the docs:
http://download.java.net/jdk7/archive/b123/docs/api/java/lang/Character.html#isDigit(char)
So, you could do something like this...
String character = in.next();
char c = character.charAt(0);
...
if (Character.isDigit(c)) {
...
} else if (Character.isLetter(c)) {
...
}
...
If you ever want to know exactly how this is implemented, you could always look at the Java source code.
Ummm, you guys are forgetting the Character.isLetterOrDigit method:
boolean x;
String character = in.next();
char c = character.charAt(0);
if(Character.isLetterOrDigit(charAt(c)))
{
x = true;
}
This is a little tricky, the value you enter at keyboard, is a String value, so you have to pitch the first character with method line.chartAt(0) where, 0 is the index of the first character, and store this value in a char variable as in char c= line.charAt(0)
now with the use of method isDigit() and isLetter() from class Character you can differentiate between a Digit and Letter.
here is a code for your program:
import java.util.Scanner;
class Practice
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Input a letter");
String line = in.nextLine();
char c = line.charAt(0);
if( Character.isDigit(c))
System.out.println(c +" Is a digit");
else if (Character.isLetter(c))
System.out.println(c +" Is a Letter");
}
}
By using regular expressions:
boolean isChar = character.matches("[a-zA-z]{1}");
boolean isDigit = character.matches("\\d{1}");
char charInt=character.charAt(0);
if(charInt>=48 && charInt<=57){
System.out.println("not character");
}
else
System.out.println("Character");
Look for ASCII table to see how the int value are hardcoded .
This is the way how to check whether a given character is alphabet or not
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0);
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
System.out.println(c + " is an alphabet.");
else
System.out.println(c + " is not an alphabet.");
}
char temp = yourString.charAt(0);
if(Character.isDigit(temp))
{
..........
}else if (Character.isLetter(temp))
{
......
}else
{
....
}
import java.util.*;
public class String_char
{
public static void main(String arg[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the value");
String data;
data = in.next();
int len = data.length();
for (int i = 0 ; i < len ; i++){
char ch = data.charAt(i);
if ((ch >= '0' && ch <= '9')){
System.out.println("Number ");
}
else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
System.out.println("Character");
}
else{
System.out.println("Symbol");
}
}
}
}
You need to convert your string into character..
String character = in.next();
char myChar = character.charAt(0);
if (Character.isDigit(myChar)) {
// print true
}
Check Character for other methods..
You could do this by Regular Expression as follows
you could use this code
EditText et = (EditText) findViewById(R.id.editText);
String NumberPattern = "[0-9]+";
String Number = et.getText().toString();
if (Number.matches(NumberPattern) && s.length() > 0)
{
//code for number
}
else
{
//code for incorrect number pattern
}
I have coded a sample program that checks if a string contains a number in it! I guess it will serve for this purpose as well.
public class test {
public static void main(String[] args) {
String c;
boolean b;
System.out.println("Enter the value");
Scanner s = new Scanner(System.in);
c = s.next();
b = containsNumber(c);
try {
if (b == true) {
throw new CharacterFormatException();
} else {
System.out.println("Valid String \t" + c);
}
} catch (CharacterFormatException ex) {
System.out.println("Exception Raised-Contains Number");
}
}
static boolean containsNumber(String c) {
char[] ch = new char[10];
ch = c.toCharArray();
for (int i = 0; i < ch.length; i++) {
if ((ch[i] >= 48) && (ch[i] <= 57)) {
return true;
}
}
return false;
}
}
CharacterFormatException is a user defined Exception. Suggest me if any changes can be made.

Categories