What's wrong with my Counting Vowels Application? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
So I was given this assignment in class to make a counting vowel application. I have no idea what's wrong with my code, but please take a look.
package com.practice;
import java.util.*;
public class CountVowels {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
int vowels = 0;
System.out.print("Enter text: ");
String text = input.nextLine();
int last = text.length() - 1;
while (last > 0) {
char temp = text.charAt(counter);
if (temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u') {
vowels++;
}
counter++;
last++;
}
System.out.println("The number of vowels are: " + vowels);
}
}

Your program have infinity cycle and therefore calls IndexOfBoundException. If U want to loop cycle from end U need to decrement your last variable. Write --last; instead of last++ and change your cycle condition on while (last >= 0). To loop from start to end of your string change int last = text.length() - 1; on int last = 0; and your cycle condition on while (last < text.length()). You can choose a lot of different ways to solve this problem, but the main thing that you have understood the point.

You have to make your mistake correct as follows
Scanner input = new Scanner(System.in);
int vowels = 0;
System.out.print("Enter text: ");
String text = input.nextLine();
System.out.println(text);
int last = text.length() - 1;
while (last >= 0) {
char temp = text.charAt(last);
if (temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u') {
vowels++;
}
last--;
// in your case this one ++ cause StringIndexOutOfBoundsException
}
System.out.println("The number of vowels are: " + vowels);

public static void main(String[] args){
Scanner input = new Scanner(System.in);
int vowels = 0;
System.out.print("Enter text: ");
String text = input.nextLine();
int last = text.length() - 1;
for(int i=0;i<text.length();i++)
{
char temp = text.charAt(i);
if (temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u') {
vowels++;
}
}
System.out.println("The number of vowels are: " + vowels);
}
The Output is:
Enter text: santhosh
The number of vowels are: 2

Related

Nothing seems to happen when I try to count vowels and consonants

I need to use while loop.
error: bad operand type for binary operator ||.
first type: boolean
secod type: char
Assume that the letters A, E, I, O and U are vowels; any thing else is
consonant. Write a program that prompts the user to enter a string
(that consists only of letters - no numbers), and displays the number
of vowels and consonants in the string. Use a while loop.
Here is my code:
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = input.nextLine();
s = s.toUpperCase().trim();
int vowels = 0;
int consonants = 0;
int i = 0;
while (i < s.length()){
char ch = s.charAt(i);
if(ch == 'A' || ch == 'E' || ch == 'I'|| ch = 'O' || ch == 'U')
{
++vowels;
}
else {
consonants++;
}
i++;
System.out.println("The number of vowels is " + vowels);
System.out.println("The number of consonants is " + consonants);
}
}
}
I found another solution for my program. Below you can see the new program. This one is running. No problems.
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = input.nextLine();
int vowels = 0;
int consonants = 0;
int i = 0;
while (i < s.length()){
if (Character.isLetter(s.charAt(i))) {
if (Character.toUpperCase(s.charAt(i)) == 'A' ||
Character.toUpperCase(s.charAt(i)) == 'E' ||
Character.toUpperCase(s.charAt(i)) == 'I' ||
Character.toUpperCase(s.charAt(i)) == 'O' ||
Character.toUpperCase(s.charAt(i)) == 'U')
vowels++;
}else{
consonants++;
}
i++;
}
System.out.println("The number of vowels is " + vowels);
System.out.println("The number of consonants is " + consonants);
OUTPUT:
run:
Enter a sentence: We need to plan the next summer
The number of vowels is 9
The number of consonants is 6
BUILD SUCCESSFUL (total time: 1 minute 0 seconds)

Do while loop for Try again program not working correctly (java)

I created a program that convert text to ASCII value and now when i press Y to try again and input a new string there will be a error that string is out of range etc.
I am new in this field, I will appreciate your help.
And here is the Error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 17,length 17
at java.base/java.lang.String.checkIndex(String.java:3278)
at java.base/java.lang.AbstractStringBuilder.charAt(AbstractStringBuilder.java:307)
at java.base/java.lang.StringBuffer.charAt(StringBuffer.java:242)
at com.company.Main.main(Main.java:26)
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
boolean Flag; // The Boolean variable for the do while lopp
int n,l,j=0,m,i,ch;
char t;
StringBuffer data = new StringBuffer();
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter any string and it will convert into numbers:- ");
data.append(input.nextLine());
l = data.length();
m = l;
System.out.println(l);
for (i = 0; i < m; i++) {
t = data.charAt(j);
n = (int) t;
System.out.print(n);
System.out.print(",");
j++;
}
data.delete(0, m-1);
System.out.println("\nDo you want to try again? Y/N");
ch = input.nextInt();
//Those are the condition for that the program should be run again or not
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
}
while(Flag=true);
System.out.println("Thanks, Come Again");
}
}
while(Flag=true);
this doesn't check whether the value of Flag is true, it sets it to true, and thus automatically returns true.
What you want is:
while(Flag==true);
or,
while(Flag);
for short.
You may also want to read up about naming conventions.
As for your Exception:
Y is not an int, change your
ch = input.nextInt();
to
ch = input.nextLine().charAt(0);
this will solve the initial problem, but still might lead to false results with unexpected input (or lack there of)
int n,l,j=0,m,i,ch;
This declaration is invalid. If all of these values are supposed to be
0, the declaration should look like:
int n, l, j, m, i, ch = 0
Also your logic in the nextInput section is incorrect.
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
Instead of the AND ( && ) this should be an OR ( || ). If it's 'Y' OR it's 'y'. It will likely never be both Y and y. This should be fixed as follows:
if (ch == 'Y' || ch == 'y') {
Flag = true;
} else if (ch == 'N' || ch == 'n') {
Flag = false;
}
Also, as mentioned by #Stultuske, you'll want to change your while condition to:
while (Flag == true)
One thing that's niggling at me here is that ch is an integer, but you're asking it if that value is 'Y, y, N, n' those are characters and not integers. I'm guessing that's why you got the 'Input_Mismatch_Exception'. Hope this helps.
Edit: Formatting

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);
}
}

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