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);
}
}
Related
I am a complete noob to Java, but I wish to make a program that takes an input from user, [A/a] - [C/c], [D/d] - [F/f], and so on, and then returns a value ([A/a-C/c = 1], [D/d-F/f = 2]....
If the input is not A-Z or a-z, returns a "Invalid input". (I think I can figure this one out myself).
I suppose I could make a "ToUpperCase" statement on the input, but I am not entirely sure how to do so.
I would prefer not to use any special databases.
Here is my code so far:
import java.util.Scanner;
public class TelefonTastatur {
public static void main(String[] args) {
String korrTall = "Korresponderer til tallet "; //Strings are in Norwegian, but I don't need help with those :-)
System.out.println("Dette programmet konverterer bokstav-input til korresponderende tall på et telefontastatur.");
System.out.println("Oppgi en bokstav (A-Z: "); //Asks user for A-Z input.
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0); //Perhaps toUpperCase to lower number of switch cases?
switch (c) {
case ('A'-'C'): //Not sure how to make A-C and/or a-c. I could make an individual case for all inputs, but that would make a lot of code.
case ('a'-'c'):
System.out.print(korrTall + "2.");
break;
case (D/d - F/f):
case ():
System.out.print(korrTall + "3.");
break;
case (G/g - I/i):
case ():
System.out.print(korrTall + "4.");
break;
case (J/j - L/l):
case ():
System.out.print(korrTall + "5.");
break;
case (M/m - O/o):
case ():
System.out.print(korrTall + "6.");
break;
case (P/p - S/s):
case ():
System.out.print(korrTall + "7.");
break;
case (T/t - V/v):
case ():
System.out.print(korrTall + "8.");
break;
case (W/w - Z/z):
case ():
System.out.print(korrTall + "9.");
break;
case 'F':
case 'f':
System.out.print(korrTall + "0.");
break;
default:
System.out.println("Det du har tastet inn tilsvarer ikke noe tall på et telefontastatur.");
break;
}
}
}
If you want to read a single letter from the user you can use the readInput()provided in the code snippet.
Then, for example in your main(), you could ask for the user to input 2 letters and then you will provide him the result.
public static void main(String[] args) {
try{
char inputOne = readInput();
char inputTwo = readInput();
handle(inputOne,inputTwo);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
static char readInput(){
System.out.println("Insert a character");
String input = Console.readLine();
if (input.length==0) {
char c = input.charAt(0);
if (Character.isLetter(c)) {
return c;
}
}
throw new Exception("Invalid input!");
}
static void handle(char a, char b){
// your logic to handle the input of the user
}
Your question is not clear at all but i try to help you. Next time post what u tried.
This simple code will help you, this can be improved so let's do this :D
Scanner scanner = new Scanner(System.in);
System.out.println("Insert first char");
String firstChar = scanner.next().toUpperCase();
if (firstChar.length() != 1 || (firstChar.toCharArray()[0] < 65 || firstChar.toCharArray()[0] > 90)) {
System.out.println("Please, insert one single character [a-z/A-Z]");
return;
}
System.out.println("Insert second char");
String secondChar = scanner.next().toUpperCase();
if (secondChar.length() != 1 || (secondChar.toCharArray()[0] < 65 || firstChar.toCharArray()[0] > 90)) {
System.out.println("Please, insert one single character");
return;
}
System.out.println(firstChar + " - " + secondChar + " = " + Math.abs(firstChar.toCharArray()[0] - secondChar.toCharArray()[0]));
Note that You can create methods to do repetitive action. In this simple example you can create a method that check if what you just read from keyboard is a single character.
One other improve you can do is handle when user insert something wrong.
Let's try to code :D
Bye
You're going to have to use the Scanner class to accomplish user input.
import java.util.Scanner;
Then create a variable that takes in the keyboard input.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a letter: ");
String text = keyboard.nextLine();
Create a method that returns a number given a character.
a-z is equal to 97-122 in Java, and A-Z is equal to 65-90.
public int toNum(String text) {
//Ensure that the text is only 1 character long.
if(text.length() > 1) return -1;
//Convert the one-character String to type char.
char letter = text.charAt(0);
//Convert char to its equivalent number value.
int rawNum = letter;
int newNum;
//Convert the number to a value 0-25.
if(rawNum >= 'a' && rawNum <= 'z') {
newNum = rawNum - 'a';
} else if(rawNum >= 'A' && rawNum <= 'Z') {
newNum = rawNum - 'A';
} else {
//None of the characters were letters A-Z.
System.out.println("Invalid input");
return -1;
}
//If {a,b,c} are 1 and {d,e,f} are 2, then {0,1,2} -> 1 and {3,4,5} -> 2
//Take the floor of the new number divided by 3.
int toReturn = Math.floor(newNum / 3.0) + 1;
return toReturn;
}
Now just call your method with the user input.
toNum(text);
You can print the returned value of the user input as well.
System.out.println(toNum(text));
This question already has answers here:
User input to repeat program in Java
(8 answers)
Closed 6 years ago.
How do I get it to loop to see if they have more then one word to translate? I think that I'm on the right track to have it repeat, have to just be missing a small detail I can't see.
Thanks!
So here is my code:
import java.util.Scanner;
public class holdingCode
{
public static void main (String[] args)
{
System.out.println("Please enter a word to be translated: ");
Scanner in = new Scanner(System.in);
//Grabs a word for the user to translate further down
String answer = "";
do
{
String newWord = in.nextLine();
newWord = newWord.toUpperCase();
char vowel = Character.toLowerCase(newWord.charAt(0));
if (vowel == 'a' || vowel == 'e' || vowel == 'i' || vowel == 'o' || vowel == 'u')
{
String pigLatinWay = newWord + "WAY";
System.out.println("Your word in pig latin is " + pigLatinWay + ".");
System.out.println("Do you have another word to translate? (Y/N)");
answer = in.nextLine();
//converts if it is a vowel
}//end of if code
else
{
if (true)
{
String first = newWord.substring(0,1);
String slice = newWord.substring(1,newWord.length());
System.out.println(" Your translated word is " + slice + first + "AY");
System.out.println("Do you have another word to translate? (Y/N)");
answer = in.nextLine();
//converts if it isn't a vowel
}//end of if code
}//end of else code
}
while (answer.equalsIgnoreCase("Y"));
}//end of pigLatin
}//end of program
The scope of String anwser = in.nextLine(); is restricted to the blocks that it is defined in
so try
after
newWord = newWord.toUpperCase();
String answer = "";
in block
anwser = in.nextLine();
and finally your comparison
while (anwser.equalsIgnoreCase("Y"));
edit
To summarize you can do
String answer;
do
{
String newWord = in.nextLine();
newWord = newWord.toUpperCase();
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.
it doesn't realize that there is an if statement when i type a consonant.
and also when i type e, it realizes that its a consonant.
Also when i enter "a" it produces the if statment for string vowel and the else statement.
same with captial letter "A" but this time it produces the else twice.
import javax.swing.JOptionPane;
public class R
{
public static void main(String args[])
{
String[] vowels = {"a","e","i","o","u"};
String[] vowel = {"A","E","I","O","U"};
String InputVowel = JOptionPane.showInputDialog(null,"Enter a Character: ");
for (int x=0;x<vowels.length;x++)
{
if(InputVowel.equals (vowels[x]))
JOptionPane.showMessageDialog(null,InputVowel+" is a lowercase");
if(InputVowel.equals(vowel[x]))
JOptionPane.showMessageDialog(null,InputVowel+" is an uppercase");
else
x = 5;
JOptionPane.showMessageDialog(null,InputVowel+" is a consaunant");
}
}
}
The reason it can't recognize your if-statements is braces are required if you have more than one if-statement check. If you have an if-else, braces are required.
String[] vowels = {"a","e","i","o","u"};
String[] vowel = {"A","E","I","O","U"};
String InputVowel = JOptionPane.showInputDialog(null,"Enter a Character: ");
for (int x=0;x<vowels.length;x++) {
if(InputVowel.equals (vowels[x])) {
JOptionPane.showMessageDialog(null,InputVowel+" is a lowercase");
} else if(InputVowel.equals(vowel[x])) {
JOptionPane.showMessageDialog(null,InputVowel+" is an uppercase");
} else {
x = 5;
JOptionPane.showMessageDialog(null,InputVowel+" is an consaunant");
}
}
The above code should work.
You can only assume it is not a vowel after checking all candidates (all vowels)
String[] vowels = {"a","e","i","o","u"};
String[] vowel = {"A","E","I","O","U"};
String InputVowel = JOptionPane.showInputDialog(null,"Enter a Character: ");
boolean isVowel = false;
for (int x=0;x<vowels.length;x++)
{
if(InputVowel.equals (vowels[x])) {
JOptionPane.showMessageDialog(null,InputVowel+" is a lowercase");
isVowel = true;
break;
}
if(InputVowel.equals(vowel[x])) {
JOptionPane.showMessageDialog(null,InputVowel+" is an uppercase");
isVowel = true;
break;
}
}
if (!isVowel)
JOptionPane.showMessageDialog(null,InputVowel+" is an consaunant");
Although the OP has already accepted an answer. This is an enhanced version of the program utilizing various features of the program.
import javax.swing.JOptionPane;
public class R
{
public static void main(String args[]){
String[] vowels = {"a","e","i","o","u"};
String InputVowel = JOptionPane.showInputDialog(null,"Enter a Character: ").trim();
String x = Integer.toHexString(InputVowel.charAt(0));
for(int i=0;i<vowels.length;i++)
{
if(vowels[i].equalsIgnoreCase(InputVowel))
{
if(!(InputVowel.equals(vowels[i].toUpperCase())))
JOptionPane.showMessageDialog(null,InputVowel+" is a vowel and lowercase character");
else
JOptionPane.showMessageDialog(null,InputVowel+" is a vowel and uppercase character");
break;
}
else if(InputVowel.length()>1||(Integer.valueOf(x)>=0 && Integer.valueOf(x)<=40))
{JOptionPane.showMessageDialog(null,InputVowel+" is not a valid character");break;}
else
{
if(!InputVowel.equals(vowels[i].toUpperCase()))
JOptionPane.showMessageDialog(null,InputVowel+" is a consonant and lowercase character");
else
JOptionPane.showMessageDialog(null,InputVowel+" is a consonant and uppercase character");
break;
}
}
}
}
Note
The input other than letters are handled (numbers and special characters) and for simplicity are labelled as non valid characters.
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++;
}