Counting the vowels in each name, and displaying separately - java

How I would get this code to count the vowels in each word rather than adding all the vowels up and displaying these. The code I have written:
import javax.swing.JOptionPane;
import java.util.Arrays;
String[] names = new String[12];
int i;
int j;
j=0;
int vowelCount;
vowelCount=0;
char ch;
names[0] = JOptionPane.showInputDialog("Please enter a name");
names[1] = JOptionPane.showInputDialog("Please enter a name");
names[2] = JOptionPane.showInputDialog("Please enter a name");
names[3] = JOptionPane.showInputDialog("Please enter a name");
names[4] = JOptionPane.showInputDialog("Please enter a name");
names[5] = JOptionPane.showInputDialog("Please enter a name");
names[6] = JOptionPane.showInputDialog("Please enter a name");
names[7] = JOptionPane.showInputDialog("Please enter a name");
names[8] = JOptionPane.showInputDialog("Please enter a name");
names[9] = JOptionPane.showInputDialog("Please enter a name");
names[10] = JOptionPane.showInputDialog("Please enter a name");
names[11] = JOptionPane.showInputDialog("Please enter a name");
Arrays.sort(names);
System.out.println("Name" + " " + "Characters" + " " + "Vowels");
for (i=0; i<12; i++)
{
for(j=0; j<names[i].length(); j++)
{
ch=names[i].charAt(j);
if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
vowelCount ++;
}
System.out.println(names[i] + " " +names[i].length() + " " + vowelCount);
}
I need the code to accept a user inputted name (which it does), sort the names alphabetically (which it does), count the characters in each name (which it does), and then display the vowels in each name.

Keep a collection of some sort, most likely an ArrayList. As you count the number of vowels, add them to the list.
//declare collection here
for(j=0; j<names[i].length(); j++)
{
ch=names[i].charAt(j);
if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
vowelCount ++;
//add ch character to collection
}
System.out.println(names[i] + " " +names[i].length() + " " + vowelCount);
//print vowels in collection
Example use of ArrayList
Just for extra information if you are interested, there are a number of collections you can use depending on whether you need a value/key pair, if you can allow duplicate entries, and if you want a certain order. Additionally, they perform differently depending on how you are using them.
Comparison Chart between different Collection

Related

How can I get the password to return back to password request if an invalid password is entered in Java?

I am trying to get the password to return and re-ask for the password if an invalid password is entered. And if a password is invalid 3 consecutive times, the system should terminate.
Is there an issue how I have structured the sequence of the lines of code? Please advise as I am rather new to Java.
public static void main(String []args){
final int MAX=10;
int invalidCount = 0;
final int MIN_Uppercase=1;
int uppercaseCounter=0;
int digitCounter=0;
int specialCounter=0;
System.out.println("Enter the password\n");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
for (int i=0; i < password.length(); i++ ) {
char c = password.charAt(i);
if(Character.isDigit(c))
digitCounter++;
if(Character.isUpperCase(c))
uppercaseCounter++;
if(c == '!' || c == '#' || c == '#' || c == '$' || c == '%' || c == '^' || c == '&' || c == '*' || c == '(' || c == ')' || c == '-' || c == '_' || c == '=' || c == '+'){
specialCounter++;
}
}
if (password.length() >= MAX && uppercaseCounter >= 1 && specialCounter == 1 && (digitCounter == 2 || digitCounter == 3)) {
System.out.println("Valid Password");
}
else {
invalidCount++;
if(password.length() < MAX)
System.out.println("Enter atleast 10 characters");
if (uppercaseCounter < MIN_Uppercase)
System.out.println("Enter at least 1 uppercase character");
if(digitCounter != 2 && digitCounter != 3)
System.out.println("Enter either 2 or 3 digits only");
if(specialCounter != 1)
System.out.println("Password must contain 1 special character");
if (invalidCount == 3)
System.out.println("Maximum tries reached");
System.exit(invalidCount);
}
return;
}
You need to put this entire logic in a while loop that keeps tracks of invalidCount.
The other solution is to put the entire logic in a while loop which is always true and it breaks out of the loop in case correct password is entered.
Also, by seeing the if condition in your code, I would like to point out only the first println statement is inside the if part and not the second println statement.
if (invalidCount == 3)
System.out.println("Maximum tries reached");
System.exit(invalidCount);
but i think you wanted to put it something like this. such that when the count reaches 3, then it should terminate.
if (invalidCount == 3) {
System.out.println("Maximum tries reached");
System.exit(invalidCount);
}
Place the Password prompt into a while loop with a counter, for example:
Scanner userInput = new Scanner(System.in);
int maxPasswordAttempts = 3;
int passwordCounter = 0;
String password = "";
while (password.isEmpty()) {
passwordCounter++;
if (passwordCounter > maxPasswordAttempts) {
System.out.println("Maximum allowable password attempts (" + maxPasswordAttempts
+ ")has been\ncarried out! No longer accepting a passwords!");
System.exit(0);
}
System.out.print("Please enter a password (c to cancel): --> ");
password = userInput.nextLine().trim();
if (password.equalsIgnoreCase("c")) {
System.out.println("Password Entry - CANCELED!");
return;
}
/* Regex from the website:
https://mkyong.com/regular-expressions/how-to-validate-password-with-regular-expression/
Give it a read... */
if (!password.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!##&()–[{}]:;',?/%*~$^+=<>]).{8,20}$")) {
System.out.println();
System.out.println("INVALID PASSWORD! - Secure Password requirements:\n" +
"-------------------------------------------------\n" +
"Password must contain at least one digit [0-9].\n" +
"Password must contain at least one lowercase Latin character [a-z].\n" +
"Password must contain at least one uppercase Latin character [A-Z].\n" +
"Password must contain at least one special character like: ! # # & ( ). %, etc.\n" +
"Password must contain a length of at least 8 characters and a maximum of 20 characters.\n" +
"Try Again...\n");
password = "";
}
}
System.out.println("\nYour VALID password is: " + password);
System.out.println("Now HASH it! :)");

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)

how i print vowels and what they are?

Everytime i input my sentence it prints out the outcome each time it goes through the loop. i assume i have to put the printlines outside the loop?
import java.util.*;
public class homework4{
public static void main(String[] args) {
//Scanner
Scanner keyBd = new Scanner(System.in);
System.out.println("Enter a sentence ");
String userIn = keyBd.nextLine();
int count = 0;
String empty= "";
//Code
for (int i = 0; i < userIn.length(); i++) {
char ch = userIn.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
System.out.println("There are " + count + " vowels in this string");
}
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
empty += ch + " ";
System.out.println("The vowels are: " + empty);
}
}
}
}
import java.util.*;
public class homework4{
public static void main(String[] args) {
//Scanner
Scanner keyBd = new Scanner(System.in);
System.out.println("Enter a sentence ");
String userIn = keyBd.nextLine();
int count = 0;
String empty= "";
//Code
for (int i = 0; i < userIn.length(); i++) {
char ch = userIn.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
empty += ch + " ";
}
}
System.out.println("There are " + count + " vowels in this string");
System.out.println("The vowels are: " + empty);
}
}
No need to check condition two times. As you are updating variables (count & empty) in loop, have to print only once after exiting from loop.
you just need to move the print statement outside and put a check condition if the count is still zero then it means there were no vowels and if count is not zero you can print it.
import java.util.Scanner;
public class homework4 {
public static void main(String[] args) {
//Scanner
Scanner keyBd = new Scanner(System.in);
System.out.println("Enter a sentence ");
String userIn = keyBd.nextLine();
int count = 0;
String empty = "";
//Code
for (int i = 0; i < userIn.length(); i++) {
char ch = userIn.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
empty += ch + " ";
}
}
if(count == 0){
System.out.println("There are no vowels in the input string");
}else {
System.out.println("There are " + count + " vowels in this string");
System.out.println("The vowels are: " + empty);
}
}
}
You don't need to test for vowels twice? (and add to count twice), only once:-
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'){
count++;
empty += ch + " ";
}
And your print statement doesn't need to happen every time you find a vowel:-
for (int i = 0; i < userIn.length(); i++) {
// not in here
}
System.out.println("There are " + count + " vowels in this string\n" + "The vowels are: " + empty);
Additionally...
If statements are ugly here, where there are many conditions. A switch would be easier to read and more efficient:-
switch (ch){
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
count++;
empty += ch + " ";
break;
}
Or move the whole condition into a method
public boolean isVowel(char c){
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U');
}
and use
if (isVowel(ch)){
//...
}

vowel counter and display the letter

public class vowel {
public static void main(String args[])
{
String sentence;
int vowels = 0, digits = 0, blanks = 0, consonants=0;
char ch;
System.out.print("Enter a String : ");
sentence = TextIO.getln();
sentence = sentence.toLowerCase();
for(int i = 0; i < sentence.length(); i ++)
{
ch = sentence.charAt(i);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels ++;
else if(ch =='b'|| ch == 'c' || ch == 'd'|| ch =='f' || ch =='g' ||
ch == 'h' || ch =='j' || ch =='k'|| ch =='l' || ch =='m' ||
ch == 'n' || ch =='p' || ch =='q'|| ch =='r' || ch =='s' ||
ch == 't' || ch =='v' || ch =='w'|| ch =='x' || ch =='z' ||
ch == 'y')
consonants ++;
else if(Character.isDigit(ch))
digits ++;
else if(Character.isWhitespace(ch))
blanks ++;
}
System.out.println("Vowels : " + vowels);
System.out.println("Consonants : " +consonants);
System.out.println("Digits : " + digits);
System.out.println("Blanks : " + blanks);
}
}
This program works perfectly in counting, but I wish to add on a function display the word it count
For example, input ABBCC12:
Vowels :1
Input Vowels : A
Consonants :4
Input Consonants : BBCC
Digits :2
Input Digits :12
Can I know what to do next?
Thanks in advance
It looks as though the easiest way that would fit with your current way of working would be to keep hold of a StringBuilder for each type:
vowelsStringBuilder = new StringBuilder();
and then whenever you encounter one, you add it on:
vowelsStringBuilder.append(ch);
At the end, you can then use
String vowelsString = vowelsStringBuilder.toString();
to get the final String containing all the vowels.
In fact, if you do it like this, you don't really need to count them as you go, because you can get the number of vowels at the end with vowelsString.length().

Java: How do I return user to main menu if user input is not a single alphabetic lowercase letter?

I'm trying to run a program that will allow the user to input both a char keyCharacter and a String theString. Then, using these inputs, I will mask the keyCharacter if it occurs in theString with a "$", remove the keyCharacter from the theString, and finally, count the number of times the keyCharacter occurs in theString altogether.
Every method is working fine, except the method getKeyCharacter where the user has to input a char:
The user can only enter a single letter (e.g. q, or z).
If the user enters anything other than that single letter (which can be anything from a word, phrase, sentence, special character like # or $, blank space or tabs, or just pressing enter), then the program returns the user to the original question that asks for the keyCharacter from the user. This should continue looping back to that original question until the user enters a valid input.
Since I'm still a beginner to java and loops are my weakness so far, this part is causing me a lot of trouble. I know I should be using a while loop, it is the logic behind the nested loops that is really confusing me.
From searching for possible solutions, I know there are these things called regex and try-catch exception that could help with my issue, but since we haven't gone over that explicitly in class, I'd prefer not to deal with that for now. Thank you.
Here's a paste of my code:
import java.util.*;
public class Foothill {
// main method
public static void main (String[] args) {
char keyCharacter = getKeyCharacter();
String theString = getString();
maskCharacter(theString, keyCharacter);
countKey(theString, keyCharacter);
removeCharacter(theString, keyCharacter);
}
// get keyCharacter
public static char getKeyCharacter() {
Scanner inputStream = new Scanner(System.in);
boolean stop = false;
String firstPrompt, strKeyCharacter;
char keyCharacter = ' ';
while (stop != true) {
firstPrompt = "Please enter a SINGLE character to act as key: ";
System.out.print(firstPrompt);
strKeyCharacter = inputStream.nextLine();
while (strKeyCharacter.length() != 1) {
firstPrompt = "Please enter a SINGLE character to act as key: ";
System.out.print(firstPrompt);
strKeyCharacter = inputStream.nextLine();
}
keyCharacter = strKeyCharacter.charAt(0);
while (strKeyCharacter.length() == 1) {
firstPrompt = "Please enter a SINGLE character to act as key: ";
System.out.print(firstPrompt);
strKeyCharacter = inputStream.nextLine();
if (keyCharacter == 'a' || keyCharacter == 'b' || keyCharacter == 'c' || keyCharacter == 'd'
|| keyCharacter == 'e' || keyCharacter == 'f' || keyCharacter == 'g' || keyCharacter == 'h'
|| keyCharacter == 'i' || keyCharacter == 'j' || keyCharacter == 'k' || keyCharacter == 'l'
|| keyCharacter == 'm' || keyCharacter == 'n' || keyCharacter == 'o' || keyCharacter == 'p'
|| keyCharacter == 'q' || keyCharacter == 'r' || keyCharacter == 's' || keyCharacter == 't'
|| keyCharacter == 'u' || keyCharacter == 'v' || keyCharacter == 'w' || keyCharacter == 'x'
|| keyCharacter == 'y' || keyCharacter == 'z') {
System.out.println("You entered: " + keyCharacter + '\n');
stop = true;
} else {
break;
}
}
}
return keyCharacter;
}
// declare final = 4 to be constant
public static final int minimumLength = 4;
// get theString
public static String getString() {
Scanner inputStream = new Scanner(System.in);
String secondPrompt, theString;
do {
secondPrompt = "Please enter a phrase or sentence >= 4: ";
System.out.print(secondPrompt);
theString = inputStream.nextLine();
System.out.print('\n');
} while (theString.length() < minimumLength || theString == null || theString.length() == 0);
inputStream.close();
return theString;
}
// mask keyCharacter with $
public static String maskCharacter(String theString, char keyCharacter) {
theString = theString.replace(keyCharacter, '$');
System.out.println("String with " + " '" + keyCharacter + "' " + " masked.");
System.out.println(theString + '\n');
return theString;
}
// count number of times keyCharacter occurs in theString
public static void countKey(String theString, char keyCharacter) {
int countChar = 0;
for (int charTimes = 0; charTimes < theString.length(); charTimes++) {
if (theString.charAt(charTimes) == keyCharacter) {
countChar++;
}
}
System.out.println( "The key character occurs " + countChar + " times. \n");
return;
}
// remove keyCharacter from theString
public static void removeCharacter(String theString, char keyCharacter) {
theString = theString.replace(String.valueOf(keyCharacter), "");
System.out.println("String with " + "'" + keyCharacter + "' removed: ");
System.out.println(theString);
return;
}
}
And here's a paste of my run (as you can see, there is some serious debugging to be done in my program):
Please enter a SINGLE character to act as key: f
Please enter a SINGLE character to act as key: f
You entered: f
Please enter a SINGLE character to act as key: f
You entered: f
Please enter a SINGLE character to act as key: f
You entered: f
Please enter a SINGLE character to act as key: f
You entered: f
Please enter a SINGLE character to act as key:
// which then continues so on so forth...
public static char getKeyCharacter(){
Scanner inputStream = new Scanner(System.in);
boolean stop = false;
String firstPrompt, strKeyCharacter;
char keyCharacter = ' ';
while(!stop){
firstPrompt = "Please enter a SINGLE character to act as key: ";
System.out.println(firstPrompt);
strKeyCharacter = inputStream.nextLine();
//check if the input contains only 1 character
boolean isSingleChar = (strKeyCharacter.length() == 1);
//check if the input character is within the ASCII code of 97 (a) to 122 (z)
boolean isValidChar =
strKeyCharacter.charAt(0) >= 97 &&
strKeyCharacter.charAt(0) <= 122;
if(isSingleChar && isValidChar){
keyCharacter = strKeyCharacter.charAt(0);
stop = true;
}
}
return keyCharacter;
}

Categories

Resources