Counting vowels in a string and wrong output? - java

I am very new to java and I was wondering if you could help me out. Here is my code:
public static void main(String[] args) {
int vowels = 0;
Scanner input = new Scanner(System.in);
System.out.println ("Enter a string: ");
String string = input.nextLine();
int length = string.length();
for (int i = 0; i <= length; i++) {
String letter = string.substring(i, ++i);
if (letter.equalsIgnoreCase("a")){vowels++;}
if (letter.equalsIgnoreCase("e")){vowels++;}
if (letter.equalsIgnoreCase("i")){vowels++;}
if (letter.equalsIgnoreCase("o")){vowels++;}
if (letter.equalsIgnoreCase("u")){vowels++;}
}
System.out.println ("The number of vowels in " + string + " is: " + vowels);
}
The number is off but I can't figure out why.

This here is wrong
string.substring(i, ++i)
because the variable i is already incremented in the for-loop
so you are basically skipping chars in the string
implement the right logic, use the right data type
int length = string.length();
for (int i = 0; i < length; i++) {
char letter = string.charAt(i);
System.out.println(letter);
if (letter == 'a') {
vowels++;
} else if (letter == 'e') {
vowels++;
} else if (letter == 'i') {
vowels++;
} else if (letter == 'o') {
vowels++;
} else if (letter == 'u') {
vowels++;
}
}

Here is another solution you could try:
The split method will split the string into a String array. Then in your for loop it will check every item in your array.
public static void main(String[] args) {
int vowels = 0;
Scanner input = new Scanner(System.in);
System.out.println ("Enter a string: ");
String string = input.nextLine();
int length = string.length();
String[] stringArray = string.split("");
for (int i = 0; i < length; i++) { //I took out the = sign in your for loop arguments.
if (stringArray[i].equalsIgnoreCase("a")){vowels++;}
if (stringArray[i].equalsIgnoreCase("e")){vowels++;}
if (stringArray[i].equalsIgnoreCase("i")){vowels++;}
if (stringArray[i].equalsIgnoreCase("o")){vowels++;}
if (stringArray[i].equalsIgnoreCase("u")){vowels++;}
}
System.out.println ("The number of vowels in " + string + " is: " + vowels);
}

Related

How to count each uppercase vowels and lowercase vowels in a string? [duplicate]

If a user enters a string: hello there
it should output
Hello has 2 vowels
There has 3 consonants.
I know this is a fairly simple code but I am getting too many ideas and getting confused.
I need a to make sure I have 2 methods for numberofVowels and capitalizeWord and both returns a result
I am getting an error and I am still trying to figure out to capitalize after I got counting vowels work
import java.util.Scanner;
public class Hwk9
{
public static void main (String args[])
{
Scanner stdin = new Scanner(System.in);
String string1;
System.out.println("Enter a string");
string1 = stdin.nextLine();
string1 = string1.toLowerCase();
}
public static int numberVowels(String string1)
{
int count = 0;
int vowels = 0;
int consonants = 0;
for (int i = 0; i < string1.length(); i++)
{
char ch = string1.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
}
}
Here is a simpler way of doing this, hope this helps:
public static void checkVowels(String s){
System.out.println("Vowel Count: " + (s.length() - s.toLowerCase().replaceAll("a|e|i|o|u|", "").length()));
//Also eliminating spaces, if any for the consonant count
System.out.println("Consonant Count: " + (s.toLowerCase().replaceAll("a|e|i|o| |u", "").length()));
}
Made something like this hope this helps, this will give vowels,consonants of each word
public static void main (String args[])
{
Scanner stdin = new Scanner(System.in);
String string1;
System.out.println("Enter a string");
string1 = stdin.nextLine();
string1 = string1.toLowerCase();
int count = 0;
int vowels = 0;
int consonants = 0;
for (String retval: string1.split(" ")){
for (int i = 0; i < retval.length(); i++)
{
char ch = retval.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
System.out.println(retval.substring(0, 1).toUpperCase() + retval.substring(1)+" has "+vowels+" vowels and "+consonants+" cosonants");
vowels=0;
consonants=0;
}
}
My code without scanner and maybe not very simple, but:
public class Main{
public static void main(String[] args) {
String test = "qwertyYVTA";
test = test.trim();
int vowels = 0;
int consonants = 0;
Pattern patternVow = Pattern.compile("[eyuioa]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcherVow = patternVow.matcher(test);
while (matcherVow.find()) {
vowels++;
}
Pattern patternCons = Pattern.compile("[wrtpsdfghjklzxcvbnm]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcherCons = patternCons.matcher(test);
while (matcherCons.find()) {
consonants++;
}
System.out.println("Vowels in test String is " + vowels);
System.out.println("Consonants in test String is " + consonants);
}
}
following code will give you vowel and Constonent count
static String VOWEL_GROUP = "AEIOUaeiou";
static String testString = "AAAASHMAIOUAXCCDIOUGGGGA"; // say this is your text
public static void main(String[] args) {
int vovelCount = 0;
int consonantCount = 0;
for (int j = testString.length() - 1; j >= 0; j--) {//outer loop
for (int i = 0; i < VOWEL_GROUP.length(); i++) { //inner loop
if (VOWEL_GROUP.charAt(i) == testString.charAt(j)) {
vovelCount++; //vowel count in text
break;
}else{
consonantCount ++;
}
}
}
System.out.println(vovelCount+" "+ consonantCount);
}
I suggest you;
to create a final vowels array,
define a bool isVowel(char c) function and use it in your if condition.
Here is the simple code for counting the number of vowels using recursion
public static int vowels(String s){
int count =0;
char c;
if(s.length()==0){
return 0;
}
else{
c =s.charAt(0);
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'){
count++;
}
return count+vowels(s.substring(1));
}
}
This looks way simple than above answers. It gets the input, converts it to lowercase then to an array of characters. A simple for loop will do the trick onwards.
import java.util.*;
public class FindVowelsConsonents {
public static void main(String[] args) {
int vowels_count = 0;
int consonents_count = 0;
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++){
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' ||
chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else
consonents_count++;
}
System.out.println(vowels_count+ " "+consonents_count);
sc.close();
}
}
As far as I am concerned you can use StringTokenizer:
String text = "dupalo twoja mama";
StringTokenizer tokenizer = new StringTokenizer(text,"aeiuo",false);
int vowels = tokenizer.countTokens();
System.out.println(vowels);
In this case of "text" it will print out 7.
import java.util.Scanner;
//don't use space in between the input string;
class StrRev {
static String Vowels ="aeiouAEIOU";
public static void main(String[] args){
#SuppressWarnings("resource")
Scanner name = new Scanner(System.in);
String nm = name.nextLine();
System.out.println();
int vowel=0;
int consonant=0;
for(int i=0;i<nm.length();i++){
for(int j=0;j<Vowels.length();j++){
if(Vowels.charAt(j)==nm.charAt(i)){
vowel++;
break;
}
}
}
consonant = nm.length()-vowel;
System.out.println("no of Vowels :"+vowel+"\nno of consonant :"+consonant);
}
}

Hangman never prints 'You won'

Just started a computer science degree and have been tasked with making a Hangman game, it seems to work find other than it doesn't print "You won" and I cannot see/figure out why it doesn't. Any help from you guys would be great.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
char[] alpha = new char[26];
Arrays.fill(alpha, ' ');
String a1 = "intro to programming";
String a2 = "computer";
String a3 = "mouse and keyboard";
String a4 = "skyrim";
String a5 = "hello world";
int selector = rand.nextInt(5) + 1;
char[] words = null;
char[] show = null;
if (selector == 1) {
words = a1.toCharArray();
show = a1.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 2) {
words = a2.toCharArray();
show = a2.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 3) {
words = a3.toCharArray();
show = a3.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 4) {
words = a4.toCharArray();
show = a4.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 5) {
words = a5.toCharArray();
show = a5.toCharArray();
Arrays.fill(show, '-');
}
int length = words.length;
System.out.println("Please enter the amount of tries you would like:");
int amount = scan.nextInt();
String guessed;
char guessedchar;
for (int i = 0; i < length; i++) {
if (words[i] == ' ') {
show[i] = ' ';
}
}
int x = 0;
while (amount >= 0) {
System.out.print("String to guess: ");
for (char n : show) {
System.out.print(n);
System.out.print(" ");
}
System.out.println(" ");
System.out.println("Number of tries left: " + amount);
System.out.print("Number of times you have tried: ");
for (char a : alpha) {
System.out.print(a);
System.out.print(" ");
}
System.out.println(" ");
System.out.println("Enter a guess");
guessed = scan.next();
guessedchar = guessed.charAt(0);
alpha[x] = guessedchar;
for (int i = 0; i < length; i++) {
if (guessedchar == words[i]) {
show[i] = guessedchar;
}
}
x = x + 1;
amount = amount - 1;
if (amount == 0) {
System.out.println("You lose");
return;
} else if (show == words) {
System.out.println("You won");
}
}
}
Convert the words and show arrays to Strings and check if they are equal with .equals(), this should then display the correct message

Repetition Structures, Procedure Method

public static void main (String args[])
{
String c = "Message";
int width;
int height;
char character;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the character : ");
character = sc.next().charAt(0);
System.out.println("Enter your width: ");
width=sc.nextInt();
System.out.println("Enter your height: ");
height=sc.nextInt();
System.out.println();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (i == 0 || i == height-1) {
System.out.print(character);
} else if (j ==width-1) {
String middle = character + " " + c + " " + character;
System.out.print(middle);
}
}
System.out.println();
}
}
}
I am trying to make the MESSAGE display in the rectangle. Also, is there a way i can move my rectangle in the center of the screen too?
That code will do your trick but please notice that this is ugly.
First you are taking the whole user input line instead of the first character.
public static void main(String args[]) {
String c = "Message";
char character;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the character : ");
character = sc.next().charAt(0);
System.out.println();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 13; j++) {
if (i == 0 || i == 2) {
System.out.print(character);
} else if (j == 0) {
String middle = character + " " + c + " " + character;
System.out.print(middle);
}
}
System.out.println();
}
}
output :
aaaaaaaaaaaaa
a Message a
aaaaaaaaaaaaa
Don't use the [for loop], the StringUtils class in Apache Commons Lang3 can help you make repeating String.
See:
http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html
there are 3 methods:
(1)static String repeat(char ch, int repeat)
Returns padding using the specified delimiter repeated to a given length.
(2)static String repeat(String str, int repeat)
Repeat a String repeat times to form a new String.
(3)static String repeat(String str, String separator, int repeat)
Repeat a String repeat times to form a new String, with a String separator injected each time.

Java phrase guessing game

Wondering how to exit if total phrase is guessed and why my vowels, spaces and consonants are not counting? Most of progam runs great just cant figure out how to exit without saying "n" to question. I am returning values for counters, don't understand?
import java.util.Scanner;
public class Prog09
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
// Initializes all string variables
String sPhrase;
String answer;
// Initializes all int variables
int vowels = 0;
int consonants = 0;
int spaces = 0;
// Initializes all char variables
char cGuess = 0;
char vGuess = 0;
boolean valid = false;
// Asks user to enter if they want to play
System.out.print("Do you want to play a game? [y/n] ");
answer = stdIn.nextLine();
// Asks user to enter the phrase
System.out.print("Please enter the phrase to guess at : ");
sPhrase = stdIn.nextLine();
// Checks if user wants to play
while (answer.equalsIgnoreCase("y"))
{
char[] phrase = new char[sPhrase.length()];
char[] tmpArr = new char[sPhrase.length()];
for(int i = 0; i < sPhrase.length();i++)
{
tmpArr[i] = sPhrase.charAt(i);
phrase[i] = sPhrase.charAt(i);
}
// Runs methods and main body of program
initTemplateArray(sPhrase, tmpArr, spaces);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
while (answer.equalsIgnoreCase("y"))
{
//getConsonant(stdIn, cGuess);
cGuess = getConsonant(stdIn, cGuess);
vGuess = getVowel(stdIn, vGuess);
isVowel(vGuess, valid);
updateTemplateArray(tmpArr, sPhrase, cGuess, vGuess, consonants, vowels);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
stdIn.nextLine();
System.out.print("Do you want to try again? [y/n]: ");
answer = stdIn.next();
vGuess = 0;
cGuess = 0;
}
}
// Prints results
System.out.println("The common phrase contained: Spaces: " + spaces + " Consonants: " + consonants + " Vowels: " + vowels);
stdIn.close();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods for program
public static int initTemplateArray(String sPhrase, char [] tmpArr, int spaces)
{
for (int i = 0; i < sPhrase.length(); i++)
{
if (sPhrase.charAt(i) == ' ')
{
spaces++;
tmpArr[i] = ' ';
}
if (!(sPhrase.charAt(i) == ' '))
{
tmpArr[i] = '?';
}
}
return spaces;
}
public static void printTemplateArray(char [] tmpArr)
{
for (int i = 0; i < tmpArr.length; i++)
{
System.out.print(tmpArr[i]);
}
System.out.println();
}
public static boolean isVowel(char c, boolean valid)
{
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
return valid = true;
}
else
{
return valid = false;
}
}
public static char getConsonant(Scanner stdIn, char cGuess)
{
while(cGuess == 'a' || cGuess == 'e' || cGuess == 'i' || cGuess == 'o' || cGuess == 'u'|| cGuess == 0)
{
System.out.print("Enter a lowercase consonant guess : ");
String myGuess = stdIn.next();
cGuess = myGuess.charAt(0);
}
return cGuess;
}
public static char getVowel(Scanner stdIn, char vGuess)
{
while(!(vGuess == 'a' || vGuess == 'e' || vGuess == 'i' || vGuess == 'o' || vGuess == 'u'))
{
System.out.print("Enter a lowercase vowel guess : ");
String newGuess = stdIn.next();
vGuess = newGuess.charAt(0);
}
return vGuess;
}
public static int updateTemplateArray(char [] tmpArr, String sPhrase, char cGuess, char vGuess, int consonants, int vowels)
{
vowels = 0;
consonants = 0;
for (int i = 0; i < tmpArr.length; i++)
{
if (cGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
consonants++;
}
if (vGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
vowels++;
}
}
return consonants & vowels;
}
public static void printHeader()
{
System.out.println("");
System.out.println(" Common Phrase");
System.out.println("---------------");
}
}
Java passes Ints by value instead of by reference, this means that updateTemplateArray doesn't modify the values of main's vowels, consonants or spaces. To fix this you could:
Make these variables global by definining them outside the scope of the main method. You would have to change the name of the parameters in the updateTemplateArray method to prevent shadowing.
Break updateTemplateArray into separate functions to count each of the vowels, consonants or spaces, and have them return the count of each. You would then call something like: vowels = countVowels(sPhrase); to populate the variables.
With the current setup, it will exit whenever answer stops being equal to 'y' Changing the value of answer at any time will exit the loop.

How to count vowels and consonants and capitalizing first letter in a string while output using a method and return result

If a user enters a string: hello there
it should output
Hello has 2 vowels
There has 3 consonants.
I know this is a fairly simple code but I am getting too many ideas and getting confused.
I need a to make sure I have 2 methods for numberofVowels and capitalizeWord and both returns a result
I am getting an error and I am still trying to figure out to capitalize after I got counting vowels work
import java.util.Scanner;
public class Hwk9
{
public static void main (String args[])
{
Scanner stdin = new Scanner(System.in);
String string1;
System.out.println("Enter a string");
string1 = stdin.nextLine();
string1 = string1.toLowerCase();
}
public static int numberVowels(String string1)
{
int count = 0;
int vowels = 0;
int consonants = 0;
for (int i = 0; i < string1.length(); i++)
{
char ch = string1.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
}
}
Here is a simpler way of doing this, hope this helps:
public static void checkVowels(String s){
System.out.println("Vowel Count: " + (s.length() - s.toLowerCase().replaceAll("a|e|i|o|u|", "").length()));
//Also eliminating spaces, if any for the consonant count
System.out.println("Consonant Count: " + (s.toLowerCase().replaceAll("a|e|i|o| |u", "").length()));
}
Made something like this hope this helps, this will give vowels,consonants of each word
public static void main (String args[])
{
Scanner stdin = new Scanner(System.in);
String string1;
System.out.println("Enter a string");
string1 = stdin.nextLine();
string1 = string1.toLowerCase();
int count = 0;
int vowels = 0;
int consonants = 0;
for (String retval: string1.split(" ")){
for (int i = 0; i < retval.length(); i++)
{
char ch = retval.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
System.out.println(retval.substring(0, 1).toUpperCase() + retval.substring(1)+" has "+vowels+" vowels and "+consonants+" cosonants");
vowels=0;
consonants=0;
}
}
My code without scanner and maybe not very simple, but:
public class Main{
public static void main(String[] args) {
String test = "qwertyYVTA";
test = test.trim();
int vowels = 0;
int consonants = 0;
Pattern patternVow = Pattern.compile("[eyuioa]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcherVow = patternVow.matcher(test);
while (matcherVow.find()) {
vowels++;
}
Pattern patternCons = Pattern.compile("[wrtpsdfghjklzxcvbnm]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcherCons = patternCons.matcher(test);
while (matcherCons.find()) {
consonants++;
}
System.out.println("Vowels in test String is " + vowels);
System.out.println("Consonants in test String is " + consonants);
}
}
following code will give you vowel and Constonent count
static String VOWEL_GROUP = "AEIOUaeiou";
static String testString = "AAAASHMAIOUAXCCDIOUGGGGA"; // say this is your text
public static void main(String[] args) {
int vovelCount = 0;
int consonantCount = 0;
for (int j = testString.length() - 1; j >= 0; j--) {//outer loop
for (int i = 0; i < VOWEL_GROUP.length(); i++) { //inner loop
if (VOWEL_GROUP.charAt(i) == testString.charAt(j)) {
vovelCount++; //vowel count in text
break;
}else{
consonantCount ++;
}
}
}
System.out.println(vovelCount+" "+ consonantCount);
}
I suggest you;
to create a final vowels array,
define a bool isVowel(char c) function and use it in your if condition.
Here is the simple code for counting the number of vowels using recursion
public static int vowels(String s){
int count =0;
char c;
if(s.length()==0){
return 0;
}
else{
c =s.charAt(0);
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'){
count++;
}
return count+vowels(s.substring(1));
}
}
This looks way simple than above answers. It gets the input, converts it to lowercase then to an array of characters. A simple for loop will do the trick onwards.
import java.util.*;
public class FindVowelsConsonents {
public static void main(String[] args) {
int vowels_count = 0;
int consonents_count = 0;
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++){
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' ||
chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else
consonents_count++;
}
System.out.println(vowels_count+ " "+consonents_count);
sc.close();
}
}
As far as I am concerned you can use StringTokenizer:
String text = "dupalo twoja mama";
StringTokenizer tokenizer = new StringTokenizer(text,"aeiuo",false);
int vowels = tokenizer.countTokens();
System.out.println(vowels);
In this case of "text" it will print out 7.
import java.util.Scanner;
//don't use space in between the input string;
class StrRev {
static String Vowels ="aeiouAEIOU";
public static void main(String[] args){
#SuppressWarnings("resource")
Scanner name = new Scanner(System.in);
String nm = name.nextLine();
System.out.println();
int vowel=0;
int consonant=0;
for(int i=0;i<nm.length();i++){
for(int j=0;j<Vowels.length();j++){
if(Vowels.charAt(j)==nm.charAt(i)){
vowel++;
break;
}
}
}
consonant = nm.length()-vowel;
System.out.println("no of Vowels :"+vowel+"\nno of consonant :"+consonant);
}
}

Categories

Resources