I am trying to write a method that will take a string, convert any letters to an int, and return all the converted ints to main, replacing the letters . I have if statements that convert all the letters to numbers, but I am having trouble making it work with a loop to convert all the letters instead of stopping after the first one. Any help would be appreciated, thanks in advance.
public class PhoneNumberChecker
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// Get the phone number
System.out.print("Phone number to convert: ");
String phoneNumber = input.nextLine();
// Process each character in the phone number for display
for (int i = 0; i < phoneNumber.length(); ++i)
{
// Get the character
char ch = phoneNumber.charAt(i);
if (Character.isLetter(ch))
ch = (Character.toUpperCase(ch));
else
System.out.print(ch);
}
System.out.println(getNumber(phoneNumber));
input.close();
// end method
}
public static String getNumber(String phoneNumber)
{
for (int i = 0; i < phoneNumber.length(); ++i)
{
char ch = phoneNumber.charAt(i);
ch = Character.toUpperCase(ch);
if (ch == 'A' || ch == 'B' || ch == 'C')
return "2";
else if
(ch == 'D' || ch == 'E' || ch == 'F')
return "3";
else if
(ch == 'G' || ch == 'H' || ch == 'I')
return "4";
else if
(ch == 'J' || ch == 'K' || ch == 'L')
return "5";
else if
(ch == 'M' || ch == 'N' || ch == 'O')
return "6";
else if
(ch == 'P' || ch == 'Q' || ch == 'R' || ch == 'S')
return "7";
else if
(ch == 'T' || ch == 'U' || ch == 'V')
return "8";
else if
(ch == 'W' || ch == 'X' || ch == 'Y' || ch == 'Z')
return "9";
}
return "";
}
}
You want to append the string results to a string that will continue to grow as you iterate over the given phone number.
Create a String variable before your loop, then simply append to that string instead of returning the strings. Then once you're done iterating the phone number you can return the String.
public static String getNumber(String phoneNumber){
String convertedNum = "";
for (int i = 0; i < phoneNumber.length(); ++i)
char ch = phoneNumber.charAt(i);
ch = Character.toUpperCase(ch);
if (ch == 'A' || ch == 'B' || ch == 'C')
convertedNum = convertedNum + "2"; //append to the string
else if(ch == 'D' || ch == 'E' || ch == 'F')
convertedNum = convertedNum + "3";
...
return convertedNum; //then return it at the end
}
You return from the method after the first character was handled. Let's modify your method:
public static String getNumber(String phoneNumber, int i)
{
//for (int i = 0; i < phoneNumber.length(); ++i)
{
char ch = phoneNumber.charAt(i);
ch = Character.toUpperCase(ch);
if (ch == 'A' || ch == 'B' || ch == 'C')
return "2";
else if
(ch == 'D' || ch == 'E' || ch == 'F')
return "3";
else if
(ch == 'G' || ch == 'H' || ch == 'I')
return "4";
else if
(ch == 'J' || ch == 'K' || ch == 'L')
return "5";
else if
(ch == 'M' || ch == 'N' || ch == 'O')
return "6";
else if
(ch == 'P' || ch == 'Q' || ch == 'R' || ch == 'S')
return "7";
else if
(ch == 'T' || ch == 'U' || ch == 'V')
return "8";
else if
(ch == 'W' || ch == 'X' || ch == 'Y' || ch == 'Z')
return "9";
}
return "";
}
Note, that it has an int parameter and the cycle was commented out. Now, let's process a String:
public static function parseString(String input) {
String output = "";
for (int i = 0; i < input.length; i++) {
output += getNumber(input, i);
}
return output;
}
Note, that this is very simple to understand. The thing which makes it simple is the fact that a method is doing a single thing. getNumber gets a number from a String at a given index. parseString parses the String in the way your code suggested. Of course you can modify the initial String if that is the purpose, using setChar, but then the getNumber method should return the char representation of the digits.
As an alternative you could use String.relaceAll instead of checking each char in a nested if-else. Example:
public static String getNumber(String phoneNumber){
String result = phoneNumber.toUpperCase()
.replaceAll("[A-C]", "2")
.replaceAll("[D-F]", "3")
.replaceAll("[G-I]", "4")
.replaceAll("[J-L]", "5")
.replaceAll("[M-O]", "6")
.replaceAll("[P-S]", "7")
.replaceAll("[T-V]", "8")
.replaceAll("[X-Z]", "9");
return result;
}
I would suggest you to use StringBuilder as compared to String as it is preferable performance wise compared to String. The reason is String is immutable. So inside the loop the String object will be created again and again. Whereas StringBuilder is mutable so it is declared only once and then can be operated on by it's reference. You can use it as shown below:
public static String getNumber(String phoneNumber){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < phoneNumber.length(); ++i){
char ch = phoneNumber.charAt(i);
ch = Character.toUpperCase(ch);
if (ch == 'A' || ch == 'B' || ch == 'C')
sb.append("2");
else if(ch == 'D' || ch == 'E' || ch == 'F')
sb.append("2");
else if(ch == 'G' || ch == 'H' || ch == 'I')
sb.append("3");
else if(ch == 'J' || ch == 'K' || ch == 'L')
sb.append("4");
else if(ch == 'M' || ch == 'N' || ch == 'O')
sb.append("5");
}
return sb.toString();
}
You can read about performance of String vs StringBuilder here. Pay attention to switch from concatination(+) to Builder.
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)){
//...
}
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
At the end of my loop, I am planning on displaying the number of consonants and vowels in the sentence. I was wondering if there was a more efficient way to check how many consonants and vowels are in a given sentence, rather than using an if statement and manually inputting every letter. (key refers to my Scanner which has already been initialized)
Edit: It needs to ignore digits and other special characters, so for example if I write Hello# how 1are you?. There should be 8 vowels and 6 consonants.
System.out.println("Please enter the sentence to analyze: ");
String words = key.nextLine(); //the sentence the user inputs
int c = 0; //# of consonants
int v = 0; //# of vowels
int length = words.length(); //length of sentence
int check; //goes over each letter in our sentence
for(check = 0; check < length; check++){
char a = words.charAt(check);
if(a == 'a' || a == 'A' || a == 'e' || a == 'E' || a == 'i' || a == 'I' || a == 'o'
|| a == 'O' || a == 'u' || a == 'U' || a == 'y' || a == 'Y')
v = v + 1;
else if(a == 'b' || a == 'B' || a == 'c' || a == 'C' || a == 'd' || a == 'D' || a == 'f'
|| a == 'F' || a == 'g' || a == 'G' || a == 'h' || a == 'H' || a == 'j' || a == 'J'
|| a == 'k' || a == 'K' || a == 'l' || a == 'L' || a == 'm' || a == 'M' || a == 'n'
|| a == 'N' || a == 'p' || a == 'P' || a == 'q' || a == 'Q' || a == 'r' || a == 'r'
|| a == 's' || a == 'S' || a == 't' || a == 'T' || a == 'v' || a == 'V' || a == 'w'
|| a == 'W' || a == 'x' || a == 'X' || a == 'z' || a == 'Z')
c = c + 1;
}
Use Character.isLetter(ch) to determine if the character is a vowel or a consonant, then check to see if the character in question is in the set of vowels.
One way to create the set of vowels:
Set<Character> vowels = new HashSet<Character>();
for (char ch : "aeiou".toCharArray()) {
vowels.add(ch);
}
And to increment v or c:
if (Character.isLetter(a)) {
if (vowels.contains(Character.toLowerCase(a))) {
v++;
} else {
c++;
}
}
Assuming you already have a letter (vowel or consonant, not a digit nor a symbol or anything else), then you can easily create a method to define if the letter is a vowel:
static final char[] vowels = { 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'y', 'Y' };
public static boolean isVowel(char c) {
for (char vowel : vowels) {
if (c == vowel) {
return true;
}
}
return false;
}
public static boolean isConsonant(char c) {
return !isVowel(c);
}
Note that I set Y and y as vowels since seems that they are in your language. In Spanish and English, Y is a consonant (AFAIK).
You can easily check if the char is a letter or not using Character#isLetter.
So, your code would become into:
for(check = 0; check < length; check++){
char a = words.charAt(check);
if (Character.isLetter(a)) {
if (isVowel(a)) {
v++;
} else {
c++;
}
}
}
How about something like
String vowels = "aeiouyAEIOUY"; // you can declare it somewhere before loop to
// to avoid redeclaring it each time in loop
//inside loop
if ((a>='a' && a<='z') || (a>='A' && a<='Z')){ //is letter
if (vowels.indexOf(a)!=-1) //is vowel
v++;
else //is consonant
c++;
}
I am sure this can be improved upon, but I'll throw it in the ring anyways.
Remove non-characters from the sentence, lowercase it, then convert to a char array and compare it to a char array of vowels that are all lowercase.
String myText = "This is a sentence.";
int v = 0;
char[] vowels = {'a','e','i','o','u'};
char[] sentence = myText.replaceAll("[^a-zA-Z]","").toLowerCase().toCharArray();
for (char letter : sentence) {
for (char vowel : vowels) {
if (letter == vowel) {
v++;
}
}
}
System.out.println("Vowels:"+ v);
System.out.println("Consonants:" + (sentence.length -v));
One easy way would be to create 2 lists:
one contains vowels (a, e, i, o, u)
the other contains consonants
Then you iterate over each character in the Java string.
See a sample below:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Counter {
public static void main(String[] args) {
String test = "the fox is in the woods";
test = test.toLowerCase();
List<Character> vowels = new ArrayList<Character>();
vowels.addAll(Arrays.asList(new Character[]{'a', 'e', 'i', 'o', 'u'}));
List<Character> consonants = new ArrayList<Character>();
consonants.addAll(Arrays.asList(new Character[]{'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'}));
int vcount = 0;
int ccount = 0;
for (int i = 0; i < test.length(); i++){
Character letter = test.charAt(i);
if (vowels.contains(letter)){
vcount ++;
} else if (consonants.contains(letter)){
ccount++;
}
}
System.out.println(vcount);
System.out.println(ccount);
}
}
You can do a range check to make sure it is a letter, then check if it one of the vowels:
if( ( a >= 'a' && a<= 'z' ) || ( a >= 'A' && a <= 'Z' ) )
{
// is letter
switch( a )
{
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'U': case 'u':
++v;
break;
default: // don't list the rest of the characters since we did the check in the if statement above.
++c;
}
}
Oh, there's certainly a much more readable way to do it. Not sure if that meets the "better" definition.
As a start, I'd suggest that you encapsulate what you have into methods that you can write once and call anywhere:
package misc;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ParseUtils get counts of vowels and consonants in sentence
* #author Michael
* #link https://stackoverflow.com/questions/24048907/how-can-i-check-how-many-consonants-and-vowels-there-are-in-a-sentence-in-java
* #since 6/4/2014 6:57 PM
*/
public class ParseUtils {
private static final String VOWEL_PATTERN_STR = "(?i)[aeiou]";
private static final Pattern VOWEL_PATTERN = Pattern.compile(VOWEL_PATTERN_STR);
private static final String CONSONANT_PATTERN_STR = "(?i)[b-df-hj-np-tv-z]";
private static final Pattern CONSONANT_PATTERN = Pattern.compile(CONSONANT_PATTERN_STR);
private ParseUtils() {}
public static void main(String[] args) {
for (String arg : args) {
System.out.println(String.format("sentence: '%s' # letters: %d # vowels: %d # consonants %d", arg, arg.length(), getNumVowels(arg), getNumConsonants(arg)));
}
}
public static int getNumVowels(String sentence) {
return getMatchCount(sentence, VOWEL_PATTERN);
}
public static int getNumConsonants(String sentence) {
return getMatchCount(sentence, CONSONANT_PATTERN);
}
private static int getMatchCount(String s, Pattern p) {
int numMatches = 0;
if ((p != null) && (s != null) && (s.trim().length() > 0)) {
Matcher m = p.matcher(s);
while (m.find()) {
++numMatches;
}
}
return numMatches;
}
}
Split the String by whitespaces and and Calculate only the number of Vowels. Then Number of consonants = Length of Sentence - No. of Vowels.
Detailed Code:
System.out.println("Please enter the sentence to analyze: ");
int v = 0;
int c = 0;
String string = key.nextLine(); //the sentence the user inputs
String[] stringArray = string.split(" ");
for(int i=0;i<stringArray.length;i++)
{
for(int j= 0; j<string.length(); j++)
{
char a = string.charAt(j);
if(a == 'a' || a == 'A' || a == 'e' || a == 'E' || a == 'i' || a == 'I' || a == 'o'
|| a == 'O' || a == 'u' || a == 'U' || a == 'y' || a == 'Y')
v = v + 1;
}
c= c+(stringArray.length)-v;
}
System.out.println("Vowels:"+v+" and Consonants:"+c);
One way to do it is to get rid of the non-letters, then vowels and consonants, and get the length of what is left:
public class CountChars {
public static final String CONSONANTS = "[BCDFGHJKLMNPQRSTVWXYZ]";
public static final String VOWELS = "[AEIOU]"; // considering Y a consonant here
public static final String NOT_LETTERS = "[\\W_0-9]";
public static void main(String[] args) {
String words = "How can I check how many consonants and vowels there are in a sentence in Java?";
String letters = words.toUpperCase().replaceAll(NOT_LETTERS, "");
System.out.println("Letters: " + letters.length());
String vowels = letters.replaceAll(CONSONANTS, "");
System.out.println("Vowels: " + vowels.length());
String consonants = letters.replaceAll(VOWELS, "");
System.out.println("Consonants: " + consonants.length());
}
}
Here is the best way of doing this:
public static void checkVowelsAndConsonants(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()));
}
I'm super new to programming so I would love to keep this simple. The compiler accepts my code, but when I run the program and type in for example the letter A I just get a ton of errors. I tried earlier using String letter instead of int letter, but I just got compiler errors stating I couldn't convert Strings to characters or something. I'm really confused and could use a quick explanation and fix so I can get a number back. Here's my code:
import java.util.Scanner;
import java.lang.String;
public class PhoneAlgorithm {
public static void main(String[] args){
int digit = -1;
Scanner in;
in = new Scanner(System.in);
System.out.print("Enter an uppercase letter to find out the corresponding digit on a telephone: ");
int letter;
letter = Integer.parseInt(in.next());
if (letter == 'A' || letter == 'B' || letter == 'C') {
digit = 2; }
else if (letter == 'D' || letter == 'E' || letter == 'F') {
digit = 3; }
else if (letter == 'G' || letter == 'H' || letter == 'I') {
digit = 4; }
else if (letter == 'J' || letter == 'K' || letter == 'L') {
digit = 5; }
else if (letter == 'M' || letter == 'N' || letter == 'O') {
digit = 6; }
else if (letter == 'P' || letter == 'Q' || letter == 'R' || letter == 'S') {
digit = 7; }
else if (letter == 'T' || letter == 'U' || letter == 'V') {
digit = 8; }
else if (letter == 'W' || letter == 'X' || letter == 'Y' || letter == 'Z') {
digit = 9; }
else if (letter >= 'a' && letter >= '3') {
System.out.print("You did not enter a valid uppercase letter. Try again!");
}
if (digit != -1) {
System.out.println("The corresponding digit on your telephone is: " + digit);
}
}
}
When you use parseInt(str), you will get an Exception if the parameter str cannot be converted to an integer.
You must use char, since you are comparing the input with single characters:
char letter;
letter = in.nextLine().charAt(0);
str.charAt(index) Returns the char value at the specified index.
I have modified your code, I guess this is what you are looking for..
import java.util.Scanner;
public class Try {
public static void main(String[] args) {
//declarations
char letter;
int digit=0;
// Asking the user to enterstring
System.out.println("Enter the string");
String enterString;
//creating a scanner object and reading the string
Scanner input = new Scanner(System.in);
enterString= input.next();
System.out.println("Entered string is "+enterString);
int temp=0;
for(int i=0;i<enterString.length();i++){
letter=(char)enterString.codePointAt(i);
if (letter == 'A' || letter == 'B' || letter == 'C') {
digit = digit*10+2; }
else if (letter == 'D' || letter == 'E' || letter == 'F') {
digit = digit*10+3; }
else if (letter == 'G' || letter == 'H' || letter == 'I') {
digit = digit*10+4; }
else if (letter == 'J' || letter == 'K' || letter == 'L') {
digit = digit*10+5; }
else if (letter == 'M' || letter == 'N' || letter == 'O') {
digit = digit*10+6; }
else if (letter == 'P' || letter == 'Q' || letter == 'R' || letter == 'S') {
digit = digit*10+7; }
else if (letter == 'T' || letter == 'U' || letter == 'V') {
digit = digit*10+8; }
else if (letter == 'W' || letter == 'X' || letter == 'Y' || letter == 'Z') {
digit = digit*10+9; }
else if (letter >= 'a' && letter >= '3') {
System.out.print("You did not enter a valid uppercase letter. Try again!");
}
/*if (digit != 0) {
System.out.println("The corresponding digit on your telephone is: " + digit);
}*/
}
if (digit != 0) {
System.out.println("The corresponding digit on your telephone is: " + digit);
}
}
}