This question already has answers here:
Use string methods to find and count vowels in a string?
(10 answers)
Closed 6 years ago.
I'm new in Java and I'm trying to solve a challenge. I have to write some words and to compare which one is longer, and how many vowels the longer one have. Also if you write "end", writing of words to end and to print something else, in our case You didn't wrote any word.
Output Example in Terminal (CMD):
Write a word, or write 'end' to end writing: test
Write a word, or write 'end' to end writing: tee
Write a word, or write 'end' to end writing: testing
Write a word, or write 'end' to end writing: end
Word testing is longest and it have 2 vowels.
Output Example if you don't write any word:
Write a word, or write 'end' to end writing:
Write a word, or write 'end' to end writing:
Write a word, or write 'end' to end writing: end
You didn't wrote any word.
Program should be coded using Scanner (Input), Switch Case and Do While. Strings should be compared using method equalsIgnoreCase().
I tried many times, and what I did is only writing and deleting code.
This is my code:
import java.util.Scanner;
public class VowelFinder {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String word = null;
int num = 0;
String max = null;
final String SENTINEL = "end";
System.out.println(" ");
do {
System.out.print("Write a word, or write `" + SENTINEL + "` to end writing: ");
word = scan.nextLine();
if(!word.equalsIgnoreCase(SENTINEL)) {
int nr = countVowels(word);
if (num <= nr) {
num = nr;
max = word;
}
}
} while (!word.equalsIgnoreCase(SENTINEL));
if (max != null) {
System.out.println(" ");
System.out.println("Word `" + max + "` is longest word, and countains " + num + " vowels.");
}
else {
System.out.println(" ");
System.out.println("You din't wrote any word !");
}
}
private static int countVowels(String word) {
int counter = 0;
int vowels = 0;
while(counter < word.length()){
char ch = word.charAt(counter++);
switch (ch) {
//Lower Case
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
//Upper Case
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'Y':
vowels++;
default:
// do nothing
}
}
return vowels;
}
}
Problem is:
When I do so in terminal (CMD)
Write a word, or write 'end' to end writing:
Write a word, or write 'end' to end writing:
Write a word, or write 'end' to end writing: end
It prints me Word ' ' is longest word, and countains 0 vowels., but it should print You didn't wrote any word.
Can someone help me ? Where I did wrong ?
It should print me You didn't wrote any word if I don't write any word.
I hope I was clear and you can help me. If I wasn't clear please ask me.
Thanks for your contribution.
change the if condition to
if (word != null && !"".equals(word.trim()) && !word.equalsIgnoreCase(SENTINEL))
I added a null check and did a trim to remove the white spaces.
I have made some changes and it worked for me...
if (max != null && !max.trim().isEmpty() && max.length()>0) {
System.out.println(" ");
System.out.println("Word `" + max + "` is longest word, and countains " + num + " vowels.");
}
You could check in countVowels() whether the current word is nothing.
private static int countVowels(String word) {
int counter = 0;
int vowels = 0;
if(word.length() == 0){
return -1;
}
...
}
The return value is less than 0 so max won't be replaced.
Related
I am new at coding and now I am learning Java. I tryed to write something like calculator. I wrote it with switch case but then I realized I must take all inputs in single line. For example in this code I took 3 inputs but in 3 different lines. But I must take 2 input and 1 char in single line. First first number second char and then third number. Can you help me ?
Public static void main(String[] args) {
int opr1,opr2,answer;
char opr;
Scanner sc =new Scanner(System.in);
System.out.println("Enter first number");
opr1=sc.nextInt();
System.out.println("Enter operation for");
opr=sc.next().charAt(0);
System.out.println("Enter second number");
opr2=sc.nextInt();
switch (opr){
case '+':
answer=opr1+opr2;
System.out.println("The answer is: " +answer);
break;
case '-':
answer=opr1-opr2;
System.out.println("The answer is: " +answer);
break;
case '*':
answer=opr1*opr2;
System.out.println("The answer is: " +answer);
break;
case '/':
if(opr2>0) {
answer = opr1 / opr2;
System.out.println("The answer is: " + answer);
}
else {
System.out.println("You can't divide to zero");
}
break;
default:
System.out.println("Unknown command");
break;
}
Try following way
System.out.print("Enter a number then operator then another number : ");
String input = scanner.nextLine(); // get the entire line after the prompt
String[] sum = input.split(" ");
Here numbers and operator separated by "space". Now, you can call them by sum array.
int num1 = Integer.parseInt(sum[0]);
String operator = sum[1]; //They are already string value
int num2 = Integer.parseInt(sum[2]);
Then, you can do as you did than.
You can try something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter number, operation and number. For example: 2+2");
String value = scanner.next();
Character operation = null;
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
Character c = value.charAt(i);
// If operation is null, the digits belongs to the first number.
if (operation == null && Character.isDigit(c)) {
a.append(c);
}
// If operation is not null, the digits belongs to the second number.
else if (operation != null && Character.isDigit(c)) {
b.append(c);
}
// It's not a digit, therefore it's the operation itself.
else {
operation = c;
}
}
Integer aNumber = Integer.valueOf(a.toString());
Integer bNumber = Integer.valueOf(b.toString());
// Switch goes here...
}
Note: didn't validate input here.
JAVA:
Write a class with a constructor that accepts a String object as its argument.
The class should have a method that returns the number of vowels in the string,
and another method that returns the number of consonants in the string.
(Spaces count as neither vowels nor consonants and should be ignored.)
Demonstrate the class in a program that performs the following steps:
The user is asked to enter a string.
The program displays the following menu:
a. Count the number of vowels in the string.
b. Count the number of consonants in the string
c. Count both the vowels and consonants in the string
d. Enter another string
e. Exit the program
I have written the code: when can you check my option d, when I am entering another String, it gives vowels and consonants count 0.
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String: ");
String input1 = sc.nextLine();
VowelsAndConsonants vc = new VowelsAndConsonants(input1.toLowerCase());
System.out.println("\nWhat would you like to do? Enter:\n" + "'a' to count the vowels\n"
+ "'b' to count consonants\n" + "'c' to count both vowels and consonants\n"
+ "'d' to enter another String\n" + "'e' to exit the program");
char input2 = sc.next().charAt(0);
while (input2 != 'e') {
if (input2 == 'a') {
System.out.println("Vowels: " + vc.vowelsCount());
} else if (input2 == 'b') {
System.out.println("Consonants: " + vc.consonantCount());
} else if (input2 == 'c') {
System.out.println("Vowels: " + vc.vowelsCount());
System.out.println("Consonants: " + vc.consonantCount());
} else if (input2 == 'd') {
System.out.println("Enter another string: ");
input1 = sc.nextLine();
vc = new VowelsAndConsonants(input1.toLowerCase());
}
System.out.println("\nWhat would you like to do? Enter:\n" + "'a' to count the vowels\n"
+ "'b' to count consonants\n" + "'c' to count both vowels and consonants\n"
+ "'d' to enter another String\n" + "'e' to exit the program");
input2 = sc.next().charAt(0);
}
System.out.println("Have a great day!");
This is a well-known problem when you mix the next() and nextLine() methods of Scanner. When you call next() it returns the next word up until a newline character, but leaves the newline character in the buffer. The first line of the remaining input is now a blank line.
Then, when you call nextLine() it returns all the characters up to that newline; in other words, it returns zero characters, an empty string.
If you are careful to consume the extra newline with an extra call to nextLine() after calling next(), nextInt(), nextDouble(), etc. then you can mix the calls without issues, but the easiest thing to do in this case would be to always use nextLine() for any input from the user.
Here is a working program that will do what you are looking for:
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String: ");
String input1 = sc.next();
VowelsAndConsonants vc = new VowelsAndConsonants(input1.toLowerCase());
boolean flag =true;
while (flag) {
System.out.println("\nWhat would you like to do? Enter:\n" + "'a' to count the vowels\n"
+ "'b' to count consonants\n" + "'c' to count both vowels and consonants\n"
+ "'d' to enter another String\n" + "'e' to exit the program");
String input2 = sc.next();
switch (input2) {
case "a":
System.out.println("Vowels: " + vc.vowelsCount());
break;
case "b":
System.out.println("Consonants: " + vc.consonantCount());
break;
case "c":
System.out.println("Vowels: " + vc.vowelsCount());
System.out.println("Consonants: " + vc.consonantCount());
break;
case "d":
System.out.println("Enter another string: ");
input1 = sc.next();
vc = new VowelsAndConsonants(input1.toLowerCase());
break;
case "e":
flag=false;
break;
default:
System.out.println("wrong selection please try again");
}
}
System.out.println("Have a great day!");
}
}
class VowelsAndConsonants {
String str;
public VowelsAndConsonants(String str){
this.str = str;
}
public int vowelsCount(){
str = str.replaceAll("[\\W]", ""); //remove non-chars
int strLength = str.length();
str = str.replaceAll("[aeiou]", "");
return strLength-str.length();
}
public int consonantCount(){
str = str.replaceAll("[\\W]", ""); //remove non-chars
int strLength = str.length();
str = str.replaceAll("[aeiou]", "");
return str.length();
}
}
I hope this helps.
package scanner;
import java.util.Scanner;
public class GuessSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a sentence");
String sentence = sc.nextLine();
System.out.println("You entered the sentence " + sentence);
System.out.println("The number of words in the sentence is " + sentence.length());
char [] chars=sentence.toCharArray();
int count = 0;
for (char c : chars) {
switch(c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
break;
}
}
System.out.println("The numner of vowels in your sentence is " + count);
System.out.println("The percentage of vowels is " + 100 * count /sentence.length() + "%" );
}
}
Thank you to everyone who helped, I was able to get the correct outcome which i was looking for so i appreciate all the help recieved.
You want (100.0 * count / sentence.length()). You're using the % operator which is the modulo of two numbers
When you calculate the percent you do:
sentence.length() % count
But % is the modulo operator, which calculates remainder. You wanted to divide:
sentence.length() / count
However this will still not get you the right results as the scale is not right, and you are dividing incorrectly. It should be:
100 *count / sentence.length()
Or
100.0 *count / sentence.length()
If you want to avoid truncation
Output:
You entered the sentence Hello World
The number of words in the sentence is 11
The numner of vowels in your sentence is 3
The percentage of vowels is 27%
You are not using correct operator. modulus(%) gives you the remainder after the division. You need to use division (/) operation. You may want to use double/float for getting accurate value.
I'm working on a program for school where I need to sort how many vowels are in a string along with the # of non-vowels. My teacher wants us to ask the user if they want to continue so we can provide multiple test cases without running the program more than once. I successfully got the program to loop, but my problem is that the vowel and non-vowel numbers from the previous test case carry over to the next one. I've been searching around online for the solution but I've had no luck so far. Any help would be much appreciated. (I am a noob at programming btw, I still have much to learn.)
import java.util.*;
class VowelReader
{
public static void main(String[] args)
{
String line;
int vi= 0, a = 0, e = 0, o = 0, u = 0, nonvowels = 0;
String answer = null;
Scanner scan = new Scanner (System.in);
do {
System.out.println("Enter a String to be processed for vowels: ");
line = scan.nextLine( );
for(int i = 0; i < line.length(); i++){
char c = Character.toLowerCase(line.charAt(i));
switch (c)
{
case 'a':
a++;
break;
case 'e':
e++;
break;
case 'i':
vi++;
break;
case 'o':
o++;
break;
case 'u':
u++;
default:
nonvowels++;
break;
}
}
System.out.println(line);
System.out.println("a- " +a);
System.out.println("e- " +e);
System.out.println("i- " +vi);
System.out.println("o- " +o);
System.out.println("u- " +u);
System.out.println("Non-vowels -" +nonvowels);
System.out.println("Continue?(Y/N)");
answer = scan.nextLine();
}
while( answer.toLowerCase().equals( "y" ) );
}
}
Using a Map with the key as a String you can keep track of our counts in one object. You then could put as many Maps, one for each test/string into a List. Then you can loop over the list preforming the same test(s) on different data sets.
Being homework and all I'm not going to post any code.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Design and implement an application that reads a string from the user, then determines and prints the number of vowels and consonants which appear in the string. Use a switch statement inside a loop.
A typical program output might be:
Enter a sentence
> My dog has fleas!
Sentence is : My dog has fleas!
VowelVount is : 4
ConsonantCount is : 9
My code is:
import java.util.Scanner;
public class VnC{
public static void main(String [] args){
String text;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence");
text = scan.nextLine();
System.out.println("Sentence is : " + text);
text = text.toLowerCase();
switch(text) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vowelCount++;
System.out.println("VowelCount : " + vowelCount);
break;
default:
consonanyCount++;
System.out.println("ConsonantCount is : " + consonantCount);
break;
}
}
}
You're on the right path, and almost there. You need to loop through all the characters in your input string (text). Use a for loop for this, and switch on each character as opposed to the entire string.
Check out this. Might help:
import java.util.Scanner;
public class XX{
public static void main(String [] args){
String text;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence");
text = scan.nextLine();
System.out.println("Sentence is : " + text);
text = text.toLowerCase();
int vowelCount = 0 ;
int consonantCount = 0 ;
text = text.replaceAll("[-+.^:, !]",""); // remove chars that you don't want to count
for(int i = 0; i < text.length() ;i++ ){
if(text.charAt(i)== 'a' ||text.charAt(i)== 'e' ||text.charAt(i)== 'i' ||text.charAt(i)== 'o' || text.charAt(i)== 'u')
vowelCount++;
else
consonantCount++;
}
System.out.println("VowelCount : " + vowelCount);
System.out.println("ConsonantCount is : " + consonantCount);
}
}
for (char ch : text.toCharArray()) {
switch(ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vowelCount++;
break;
default:
consonanyCount++;
break;
}
}
System.out.println("VowelCount : " + vowelCount);
System.out.println("ConsonantCount is : " + consonantCount);