Vowels are not being detected? - java

How to find a vowel in a given word?
import java.util.Scanner;
public class Test {
public static void main(String args[])
{
Scanner a =new Scanner(System.in) ;
String x=a.nextLine();
for(int i = 0;i<x.length();i++)
{
if(x.charAt(i)=='o');
System.out.println("the word has a vowel o");
break;
}
}
}

The reason for getting this output is "when i give input lets say jdbc it shows thisjdbc the word has a vowel o the word has a vowel o the word has a vowel o the word has a vowel o –" , your if statement is wrong.
When you give semi colon after the if statement, it means you are executing a empty statement.You can either remove the semicolon after your if statement
( if(x.charAt(i)=='o'){-----}) or try the below solution
I have slightly modified your code to capture and print all the vowels present in the given String.
Hope below code helps -:
public class Test {
public static void main(String args[])
{
Scanner a =new Scanner(System.in) ;
String x=a.nextLine();
for(int i = 0;i<x.length();i++)
{
if((x.charAt(i) == 'a') || (x.charAt(i) == 'e') ||(x.charAt(i) == 'i') || (x.charAt(i) == 'o') || (x.charAt(i) == 'u')) {
System.out.println("the word has a vowel -: "+x.charAt(i));
}
}
}
}

Change your if statement so it covers the print and break:
if(x.charAt(i)=='o') {
System.out.println("the word has a vowel o");
break;
}
Note that as soon as it detects the first letter 'o' it breaks.

Related

check is String vowel or consonant using java?

How do I check whether a String begins with a vowel or a consonant sound? For instance, University begins with a consonant sound; Hour begins with a vowel sound.
public static void main(String args[])
{
char ch;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a word : ");
ch = scan.next().charAt(0);
if(ch=='a' || ch=='A' || ch=='e' || ch=='E' ||
ch=='i' || ch=='I' || ch=='o' || ch=='O' ||
ch=='u' || ch=='U')
{
System.out.print("This is a Vowel");
}
else
{
System.out.print("This is not a Vowel");
}
}
You cannot do this reasonably simply by examining the first letter. Rather, you need to refer to an on-line dictionary and use the first phoneme of the pronunciation. You've already coded the simple implementation: check the first letter. However, as your counterexamples show, this is not enough.
If this is a homework assignment, please contact your instructor for access to the pronunciation file.
public static int vovelsCount(String str) {
return str.replaceAll("[^aeiou]","").length();
}
import java.util.Scanner;
/**
* Java Program to count vowels in a String. It accept a String
from command promptand count how many vowels it contains. To revise,
5 letters a, e, i, o and u are known as
vowels in English.
*/
public class VowelCounter {
public static void main(String args[]) {
System.out.println("Please enter some text");
Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
char[] letters = input.toCharArray();
int count = 0;
for (char c : letters) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
break;
default:
// no count increment
}
}
System.out.println("Number of vowels in String [" + input + "] is : " + count);
}
}

Java Replacing a Character with a Character

I am learning Java on my own and practicing using online exercises. I have only learned up until methods thus far so using an array for this exercise is beyond my scope, even though several solutions online use arrays to do what I want.
The exercise is this: Have the user enter a string with vowels. Wherever there is a vowel letter, display that vowel as a capital letter.
Example: If the user enters "apples", the correct output is ApplEs
I have this code so far:
import java.util.Scanner;
public class CapitalizeVowels {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string ~ ");
String string = keyboard.nextLine();
for (int i = 0; i < string.length(); i++) {
System.out.print(string.charAt(i));
if (string.charAt(i) == 'a' ||
string.charAt(i) == 'e' ||
string.charAt(i) == 'i' ||
string.charAt(i) == 'o' ||
string.charAt(i) == 'u') {
char upperCaseVowel = Character.toUpperCase(string.charAt(i));
System.out.print(upperCaseVowel);
// need to replace string.charAt(i) with upperCaseVowel
// find something to replace characters
}
}
}
}
When I run my code as it is, with the input string "apples", for example, I get "aAppleEs" as my output. Both the lower case vowels and the upper case vowels are being printed. I am thinking that I should replace string.charAt(i) which is the lower case vowel with upperCaseVowel but I can't find any replace() method or something to that effect for characters. I tried other things like StringBuilder, etc. but I haven't come across a solution that is simple enough to avoid arrays as I didn't learn them yet. Any help on how I can get to the proper output is highly appreciated. Thanks!
Your mistake is printing every character before testing if it's a vowel.
Instead, print each char after you've figured out what it should be. The body of your loop should be:
char next = string.charAt(i);
if (next == 'a' ||
next == 'e' ||
next == 'i' ||
next == 'o' ||
next == 'u') {
next = Character.toUpperCase(next);
}
System.out.print(next);
You may consider adding:
else {
next = Character.toLowerCase(next);
}
To enforce non vowels being lower case.
You just need to move the Sysout prior to if statement to else, to avoid printing same character twice, e.g.:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string ~ ");
String string = keyboard.nextLine();
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == 'a' || string.charAt(i) == 'e' || string.charAt(i) == 'i' || string.charAt(i) == 'o'
|| string.charAt(i) == 'u') {
char upperCaseVowel = Character.toUpperCase(string.charAt(i));
System.out.print(upperCaseVowel);
// need to replace string.charAt(i) with upperCaseVowel
// find something to replace characters
}else{
System.out.print(string.charAt(i));
}
}
}
Try this, it works for me.
class ReplaceVowel {
public static void main(String[] args) {
String words = "apples";
char converted = 0;
String w = null;
for (int i = 0; i < words.length(); i++) {
if (words.charAt(i) =='a'|| words.charAt(i)=='e'||words.charAt(i)=='i'||words.charAt(i)=='o'||words.charAt(i)=='u') {
converted = Character.toUpperCase(words.charAt(i));
w = words.replace(words.charAt(i), converted);
words = w;
} else {
converted = Character.toUpperCase(words.charAt(i));
w = words.replace(words.charAt(i), converted);
words = w;
}
}
System.out.println(words);
}
}

Writing a translator similar to pig latin

I'm writing a program in Java where I'm supposed to translate an English sentence to a language similar to pig Latin just with a few different rules.
So far I've written the code, but it only seems to translate one word at a time rather than a whole sentence. can you let me know where I went wrong? Heres my code:
import java.util.Scanner;
public class PartD {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a phrase to convert: ");
String phrase = keyboard.nextLine();
String[] words = phrase.split(" ");
for(int i = 0; i < words.length; i++ ) {
char firstLetter = (words[i].charAt(0));
if (firstLetter == 'a' || firstLetter == 'e' || firstLetter == 'i' || firstLetter == 'o' || firstLetter == 'u'){
String vowel = words[i] +"-eh";
System.out.print(vowel);
}else{
String start = words[i].substring(0,1);
String end = words[i].substring(1,phrase.length());
System.out.print(end + "-" + start + "eh" );
}
}
System.out.println( );
}
}

How to turn a user given String into Pig Latin?

Im trying to turn a string taken from the user into Pig Latin. I cannot use any special classes, methods, or arrays. I can only use a Scanner to create a object to take the string from the user and .length and .charAt, in addition to any type of looping. (Also cannot use switch statements or the break keyword)
Here is an example of what my output is suppose to be:
Enter a line of text: this is a test.
Input : this is a line of text.
Output: his-tay is-way a-way ine-lay of-way ext-tay.
Here is my code, I can only get my code to work with one word and it must have a space at the end. Only one loop works at a time depending on the loop. Im not sure what to do if I get an entire String.
I know that when the user enters a space that signals a new word, and when they enter a period, that signals the ending.
I had a hard time understanding your code. (It looks like you are trying to do it two ways at once?) Regardless, I believe I was able to understand your question. Here is a compilable and runnable example:
import java.util.Scanner;
public class PigLatin
{
public static void main(String[] args)
{
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
if (text != null && text.length() > 0)
{
int i = 0;
// this iterates through the whole string, stopping at a period or
// the end of the string, whichever is closer
while (i < text.length() && text.charAt(i) != '.')
{
// these three variables only exist in this code block,
// so they will be re-initialized to these values
// each time this while loop is executed
char first = '\0'; // don't worry about this, I just use this value as a default initializer
boolean isFirst = true;
boolean firstIsVowel = false;
// each iteration of this while loop should be a word, since it
// stops iterating when a space is encountered
while (i < text.length()
&& text.charAt(i) != ' '
&& text.charAt(i) != '.')
{
// this is the first letter in this word
if (isFirst)
{
first = text.charAt(i);
// deal with words starting in vowels
if (first == 'a' || first == 'A' || first == 'e' || first == 'E'
|| first == 'i' || first == 'I' || first == 'o' || first == 'O'
|| first == 'u' || first == 'U')
{
System.out.print(first);
firstIsVowel = true;
}
// make sure we don't read another character as the first
// character in this word
isFirst = false;
}
else
{
System.out.print(text.charAt(i));
}
i++;
}
if (firstIsVowel)
{
System.out.print("-tay ");
}
else if (first != '\0')
{
System.out.print("-" + first + "ay ");
}
i++;
}
System.out.print('\n'); //for clean otuput
}
}
}
There are a few comments in there that might help guide you through my logic. This is almost definitely not the most efficient way to do this (even with your limitations), as I only whipped it up as a example of the type of logic you could use.
You could break it up into words, then process the current word when you hit a space or period:
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
String curWord = "";
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ' || text.charAt(i) == '.') {
if (curWord.charAt(0) == 'a' || curWord.charAt(0) == 'e' ||
curWord.charAt(0) == 'i' || curWord.charAt(0) == 'o' ||
curWord.charAt(0) == 'u') {
System.out.print(curWord + "-way ");
} else {
for (int j = 1; j < curWord.length(); j++) {
System.out.print(curWord.charAt(j);
}
System.out.print("-" + curWord.charAt(0) + "ay ");
//System.out.print(curWord.substring(1)+"-"+curWord.charAt(0)+"ay ");
}
curWord = "";
} else {
curWord += text.charAt(i);
}
}

So I have this code here, it calculates the vowels in a given phrase. I'm trying to get it to repeat if the user says yes

I was wondering as to how I could get the end of the program to repeat if the user does respond with a 1. Do I need to reorganize it so that it is part of the if statement?
Scanner input = new Scanner(System.in);
System.out.println("Count Vowels \n============");
System.out.println("Type a sentence and this program will tell you\n\nhow many vowels there are (excluding 'y'):");
String string1;
string1 = input.nextLine();
string1 = string1.toLowerCase();
int vowels = 0;
int answer;
int i = 0;
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0, 1).toUpperCase() + Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 1;
}
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
answer = input.nextInt();
if (answer == 1) {
System.out.println("You have chosen to count the vowels in another phrase");
} else {
System.out.println("Have a nice day");
}
You can do this with a do/while loop. The skeleton for this kind of loop looks like this:
Scanner input = new Scanner(System.in);
do {
// do your stuff here
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
} while(input.nextInt() == 1);
System.out.println("Have a nice day");
It asks the user and evaluates the entered number in the while(input.nextInt() == 1) statement. If this comparison returns true (i.e. user entered 1), then the loops starts again. If not (i.e. user entered something else than 1), the loop stops and you'll get the "Good Bye" message instead.
you can split this up into more than one method and using one primary method call other methods inside a while loop. for example:
boolean continueCounting = false;
void countingVowels() {
//some start game method to make continueCounting = true
//something like "press 1 to start"
//if (input == 1) { continueCounting = true; }
while(continueCounting) {
String userInput = getUserInput();
countVowels(userInput); //count vowels in word from user input and prints them out to console
getPlayAgainDecision(); //ask user to put 1 or 2
if (answer == 1) {
continue
} else if (answer == 2) {
continueCounting = false;
} else {
System.out.println("incorrect input, please choose 1 or 2");
}
}
}
There are many ways to do this. A search on Google would have lead you to the correct answer in less time than it took you to ask the question. However, since you took the time to ask the question here is the answer:
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int answer = 0;
System.out.println("Count Vowels \n============");
// the do-while loop ensures that the code is executed at least once
do {
// on the first run answer equals zero, but on other runs it will equal one
if(answer == 1) {
System.out.println("You have chosen to count the vowels in another phrase");
}
System.out.println("Type a sentence and this program will tell you\n\nhow many vowels there are (excluding 'y'):");
String string1;
string1 = input.nextLine();
string1 = string1.toLowerCase();
int vowels = 0;
int i = 0;
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i'
|| letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0, 1).toUpperCase()
+ Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 1;
}
System.out.println("Would you like to check another phrase in the Vowel Counter? If so type 1 if not type 2 and press enter");
answer = input.nextInt();
} while (answer == 1);
System.out.println("Have a nice day");
}
}
In your code you assert that a letter is a vowel if it is in the set a, e, i, o and u which is true. However, the letter y can be a vowel in certain situations.
In general, the Y is a consonant when the syllable already has a vowel. Also, the Y is considered a consonant when it is used in place of the soft J sound, such as in the name Yolanda or Yoda.
In the names Bryan and Wyatt, the Y is a vowel, because it provides the only vowel sound for the first syllable of both names. For both of these names, the letter A is part of the second syllable, and therefore does not influence the nature of the Y.
You could expand on your code even more by checking if the letter y is a vowel or not.
This is a more elegant way to do the counting (I updated the code to satisfy Johnny's comment that my previous answer didn't answer OP's question. The code now loops without unnecessary code):
public static void main(String... args)
{
int answer = 0;
Scanner input = null;
do
{
input = new Scanner(System.in);
System.out.print("Type a sentence and this program will tell you\nhow many vowels there are (excluding 'y'):");
String sentence = input.nextLine();
int vowels = 0;
String temp = sentence.toUpperCase();
for (int i = 0; i < sentence.length(); i++)
{
switch((char)temp.charAt(i))
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowels++;
}
}
System.out.println("The sentence: \"" + sentence + "\" has " + vowels + " vowels");
System.out.print("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press any other key... ");
String tempNum = input.next();
try
{
answer = Integer.parseInt(tempNum);
} catch (NumberFormatException e)
{
answer = 0;
}
System.out.println();
} while (answer == 1);
input.close();
System.out.println("Have a nice day");
}
Notice that at the end, I catch a NumberFormatException for more robustness validation of the user's input.
Just put the main for loop inside a do-while loop, like so:
do
{
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0, 1).toUpperCase() +
Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 1;
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
answer = input.nextInt();
}
} while (answer == 1);
System.out.println("Have a nice day");
Additionally, there are better ways to do the counting, for example:
for (char c : string1.toCharArray())
{
c = Character.toLowerCase(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
count++;
}

Categories

Resources