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.
Related
This question already has answers here:
String contains - ignore case [duplicate]
(5 answers)
Closed 1 year ago.
My input here need to be not case-sensitive. I'll show you my code please help, I have zero idea how to do it. Do I need to re write my code for it to be not case-sensitive?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s, x;
System.out.print("Enter a sentence: ");
s = sc.nextLine();
char[] c = s.toCharArray();
int vowel=0;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u')
vowel++;
}
System.out.println("There are "+ vowel + " vowels in the sentence");
System.out.print("\nEnter a substring that you want to search: ");
x = sc.nextLine();
boolean check = s.contains(x);
if (check){
System.out.println("There is a substring '" + (x.toUpperCase()) + "' in the sentence");
}
else
System.out.println("There is no substring '" + x + "' in the sentence");
System.out.println("\nThe entered sentence in uppercase characters.");
System.out.println(s.toUpperCase());
}
Should make the string entirely to lower case or upper case. Use this while taking input:
s = sc.nextLine().toLowerCase();
and also:
x = sc.nextLine().toLowerCase();
The complete main method:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s, x;
System.out.print("Enter a sentence: ");
s = sc.nextLine().toLowerCase();
int vowel=0;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u')
vowel++;
}
System.out.println("There are "+ vowel + " vowels in the sentence");
System.out.print("\nEnter a substring that you want to search: ");
x = sc.nextLine().toLowerCase();
boolean check = s.contains(x);
if (check){
System.out.println("There is a substring '" + (x.toUpperCase()) + "' in the sentence");
}
else
System.out.println("There is no substring '" + x + "' in the sentence");
System.out.println("\nThe entered sentence in uppercase characters.");
System.out.println(s.toUpperCase());
}
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.
when i input the number it just moves ahead without letting me enter the string and shows an output
when i use sc.next();, it does not go forward without the string, but i want to use sc.nextLine(), but it is not working
public class project1
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int n;
char a;
System.out.println("Enter \n 1 for counting the total number of vowels in it \n 2 for printing the first letter of each word in a string");
n = sc.nextInt();
switch(n)
{
case 1:
int count = 0;
System.out.println("Input a string");
String str = sc.nextLine();
str = str.toLowerCase();
for(int i = 0; i < str.length(); i++)
{
a = str.charAt(i);
if(a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
count++;
}
System.out.println("There are "+ count +" vowels in the string.");
break;
case 2:
System.out.println("Input a string");
String str2 = sc.nextLine();
System.out.println("First letter of each word:");
for(int i = 0; i < str2.length(); i++)
{
a = str2.charAt(i);
if(a == ' ')
System.out.print(str2.charAt(i+1) + ", ");
}
break;
}
}
}
The sc.nextInt will only read the integer part and leave the rest on the input stream for your next scanner command. Therefor the newline character from your first entry is still available when you try to get the string input with sc.nextLine().
You could either read the entire line and convert it to an int with:
n = Integer.parseInt(sc.nextLine());
switch(n)
or you could simply add a sc.nextLine() after your sc.nextInt() to consume the rest of the input line.
n = sc.nextInt();
sc.nextLine();
switch(n)
By the way, your method for writing the first letter of each word will skip the first word and also crash if the sentence ends with a space. Maybe try String.split() instead.
Hi this code is part of my code that is supposed to check if the number string is palindrome.
I want to iterate from top to botoom of my code but it doesn't iterate at all , what is wrong ??
I searched in youtube and realized this kind of things , people usually use do-while loop so I was trying to follow the instruction but it doesn't give me what I want .
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
Here is my full code.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
char choice;
long firstNum = 0;
firstNum = getLong(" Enter the first number: ", '-');
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
public static long getLong(String prompt, char exitChar)
{
long retVal = 0;
boolean validInput = false;
String userInput = "";
Scanner kbd = new Scanner(System.in);
while (!validInput) {
System.out.println(prompt);
try
{
userInput = kbd.nextLine().trim();
if (userInput.length() > 0 && userInput.charAt(0) == exitChar)
{
System.out.println("Ending the program at the user's request");
System.exit(1);
}
retVal = Long.parseLong(userInput);
validInput = true;
}
catch (Exception ex)
{
System.out.println("That is not numeric. Try again or press " + exitChar + "to Quit");
}
}
return retVal;
}
}
Change this:
String str = kbd.nextLine().trim();
to this
String str = kbd.next();
When read choice, using nextLine() intead of next():
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.nextLine().charAt(0); // <---here, change to nextLine()
}while(choice=='y'||choice =='Y');
}
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input. so in next loop it reads last input line that will be empty string.
I am trying to make a text-based Hangman in Java.
This is my Java code:
package hangman;
import java.util.Random;
import java.util.Scanner;
import java.lang.String;
public class Hangman {
public static void main(String[] args) {
// TODO code application logic here
Scanner chez = new Scanner(System.in);
Scanner waffle = new Scanner(System.in);
Random randomGenerator = new Random();
StringBuilder displayWord = new StringBuilder("______________________________");
String theWord = null;
String preLetter;
//String sbDisplayWord;
char letter = 0;
int randomNumber;
int lengthOfWord;
int numberOfLetterInWord = 0;
int gDisplay;
int guessWordNumber = 0;
String guessWord;
RandomWord troll = new RandomWord();
randomNumber = randomGenerator.nextInt(12);
//Fill var with the word.
theWord = troll.wordDecide(randomNumber);
System.out.println ("Welcome to Hangman!");
lengthOfWord=theWord.length( );
System.out.println("This word has " + lengthOfWord + " letters.");
System.out.println("You have 20 guesses.");
for (int g =19; g >= 0; g--) {
System.out.println("If you want to guess the word, type 0. If you want to guess a letter, type 1.");
guessWordNumber=chez.nextInt();
if (guessWordNumber==0) {
System.out.println("Enter the word now. Remember, don't capitalize it.");
guessWord=waffle.nextLine();
if (guessWord.equals(theWord)) {
System.out.println("YOU WIN");
System.exit(0);
} else {
System.out.println("Sorry, this wasn't the correct word.");
}
} else if (guessWordNumber==1) {
System.out.println("Please enter the letter you wish to guess with.");
//System.out.println("It will tell you if you have guessed right for any of the letters. If it is blank, that means none of the letters match.");
preLetter=chez.nextLine();
letter=preLetter.charAt(0);
System.out.println("");
for(int i = 0; i <= lengthOfWord -1; i++ ) { //-Eshan
if (letter == theWord.charAt( i )) {
numberOfLetterInWord=i+1;
System.out.println("This letter matches with letter number " + numberOfLetterInWord + " in the word.");
displayWord.setCharAt(i, letter);
} else {
numberOfLetterInWord=i+1;
System.out.println("This letter doesn't match with letter number " + numberOfLetterInWord + " in the word.");
}
}
System.out.println("");
System.out.println("The word so far is " + displayWord);
System.out.println("");
gDisplay = g + 1;
System.out.println("You have " + gDisplay + " guesses left.");
} else {
System.exit(0);
}
}
System.out.println("GAME OVER");
System.exit(0);
}
}
package hangman;
public class RandomWord {
private static String[] wordArray = {
"psychology",
"keratin",
"nostalgia",
"pyromaniac",
"chlorophyl",
"derivative",
"unitard",
"pterodactyl",
"xylophone",
"excommunicate",
"obituary",
"infinitesimal",
"concupiscent",
};
public String wordDecide(int randomNumber) {
String theWord;
theWord = wordArray[randomNumber];
return theWord;
}
}
Netbeans is giving me this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at hangman.Hangman.main(Hangman.java:56)
Java Result: 1
This is probably happening when you call charAt(0) on a string of length 0. You should check to see that the string is not empty before calling the method.
You are getting a StringIndexOutOfBoundsException due to the fact the line
guessWordNumber = chez.nextInt();
does not consume newline characters and passes the character through to the line
preLetter = chez.nextLine();
which then doesn't block as it will have already received input. This assigns an empty String to preLetter resulting in the exception. You can use Scanner#nextLine to consume this character:
guessWordNumber = Integer.parseInt(chez.nextLine());