I am creatings a simple Java program that in the main class asks for a string (input) and then prints out how many vowels (int count) and consonants are in the string. The number of vowels works perfectly however the number of consonants double, so the string "James" has 2 vowels and 6 consonants according to my program.
public class counter {
vowels p1 = new vowels();
public int con = 0;
public int count() {
String input = p1.getInput();
int i = 0;
int count = 0;
while (i < input.length()){
if (input.charAt(i) == 'a' || input.charAt(i) == 'e' || input.charAt(i) == 'i' || input.charAt(i) == 'o' || input.charAt(i) == 'u') {
count++;
} else if (input.charAt(i) != ' ') {
con++;
}
i++;
}
return count;
}
public int con() {
return con;
}
}
You are using an instance member con for counting the consonants, and you don't initialize it at the beginning of the count method, so multiple calls to that method will result in invalid counts.
seems like you are using
int con=0;
is used for consonant count
so instead of using
else if (input.charAt(i) != ' ') {
con++;
}
simply use
else {
con++;
}
Alternate :
subtract the vowel count from string length
'com = P1.length()-count;'
Try to set the variable con to zero at the begining of the method "count".
con = 0;
I hope it works.
char ch;
for(int i = 0; i < str.length(); i ++)
{
ch = str.charAt(i);
if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
count ++;
else
con;
}
you had nod consider the case when vowels are in caps I solved this in my code
hope my code helps you in this regard thanks.Happy coding
Related
I'm making a chatbot, and it needs to break down every sentence into an array list of strings. It gives me a string index out of bounds exception whenever I use a space. I honestly don't know what to do about this, I've looked all over the forums, please help.
char tempChar;
String tempLetter;
String tempString = "";
for (int i = 1; i <= input.length(); i++) {
Scanner breakDownScan = new Scanner(input);
tempChar = breakDownScan.next().charAt(i-1);
if (tempChar != ' ' && tempChar != '.' && tempChar != '!' && tempChar != '?') {
tempLetter = Character.toString(tempChar);
tempString += tempLetter;
}
if (tempChar == ' ' || tempChar == '.' || tempChar == '!' || tempChar == '?') {
System.out.println("test");
words.add(tempString);
}
if (i == input.length()) {
breakDownScan.close();
}
}
Thank you in advanced for any and all help you can provide :D
Just use the split method. Example:
String[] words = input.split(insert your desired parser here);
I do believe you can do just the same with an Array List :)
(for the parser, use a space(" "), or what ever your words are separated by)
I've got the code to put a seven letter phrase into a phone number. The hyphen is not returning in the correct spot. I really don't know how to fix this problem. It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem!
Code:
import java.util.*;
import java.lang.*;
public class Project1 {
public static char getNumber(char letter) {
char ret = 0;
if (letter== 'A' || letter=='a' || letter== 'B' || letter=='b' || letter=='C' || letter=='c') {
return '2';
}
else if (letter== 'D' || letter=='d' || letter== 'E' || letter=='e' || letter=='F' || letter=='f') {
return '3';
}
else if (letter== 'G' || letter=='g' || letter== 'H' || letter=='h' || letter=='I' || letter=='i') {
return '4';
}
else if (letter== 'J' || letter=='j' || letter== 'K' || letter=='k' || letter=='L' || letter=='l') {
return '5';
}
else if (letter== 'M' || letter=='m' || letter== 'N' || letter=='n' || letter=='O' || letter=='o') {
return '6';
}
else if (letter== 'P' || letter=='p' || letter== 'Q' || letter=='q' || letter=='R' || letter=='r'|| letter=='S' || letter=='s') {
return '7';
}
else if (letter== 'T' || letter=='t' || letter== 'U' || letter=='u' || letter=='V' || letter=='v') {
return '8';
}
else if (letter== 'W' || letter=='w' || letter== 'X' || letter=='x' || letter=='Y' || letter=='y' || letter=='Z' || letter=='z') {
return '9';
}
if (letter == ' ')
return '-';
return ret;
}
public static void main (String[] arg) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a 7 letter phrase: ");
String number = input.nextLine();
for (int i = 0; i < 8; i++) {
System.out.print(getNumber(number.toUpperCase().charAt(i)));
}
}
}
It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem!
Here you go! A bit of regex is always good for the soul:
{
String number = input.nextLine();
final StringBuilder builder = new StringBuilder(); // Buffer the sequence.
for (int i = 0; i < 8; i++) {
builder.append(getNumber(number.toUpperCase().charAt(i)));
if (builder.toString().getCharAt(2) != '-') // If the format isn't correct, fix it
System.out.println(builder.toString().replaceFirst("(...)(.).(...)", "$1-$2$3"))
}
}
As seen from CSᵠ's comment, you can use the following universal regex instead, such that the section becomes:
builder.toString().replaceFirst("^\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*$", "$1$2$3-$4$5$6$7");
Edit: Updated regex as \N backreferences does not work in Java.
Here's a quick and dirty solution to your problem.
import java.util.*;
public class Project1 {
public static char getNumber(char letter) {
char ret = 0;
if( letter < 'A' )
{
ret = '0';
}
else if( letter < 'D' )
{
ret = '2';
}
else if( letter < 'G' )
{
ret = '3';
}
else if( letter < 'J' )
{
ret = '4';
}
else if( letter < 'M' )
{
ret = '5';
}
else if( letter < 'P' )
{
ret = '6';
}
else if( letter < 'T' )
{
ret = '7';
}
else if( letter < 'W' )
{
ret = '8';
}
else if( letter <= 'Z' )
{
ret = '9';
}
else
{
ret = '0';
}
return ret;
}
public static void main (String[] arg) {
Scanner input = new Scanner(System.in);
System.out.println( "Please enter a 7 letter phrase: " );
String number = input.nextLine().toUpperCase();
StringBuffer buff = new StringBuffer();
for( int i = 0, j = 0; j < number.length() && i < 7; j++ )
{
char c = number.charAt(j);
if( c != ' ' )
{
if( i == 3 )
{
buff.append( '-' );
}
buff.append( getNumber( c ) );
i++;
}
}
System.out.println( buff );
}
}
Key points:
There is no need to check for lower case if the alpha characters are guaranteed to be uppercase.
There is no need to uppercase the input string on each iteration of the loop. Do it once at the beginning.
I'm ignoring spaces, and always adding a hyphen before I print position 3 (ie the fourth character).
chars can be compared just like numbers, using ranges. This simplifies the amount of code quite a bit (ie. each letter within a range doesn't need to be written down).
I've tried tinkering around with this for awhile and have yet to figure out what its giving me this error. The code is far from complete but I'm just trying to figure out why it says it can't find variable ch1. Any help is greatly appreciated!
public class PhoneNumber {
String phoneNumber;
public PhoneNumber(String num) {
phoneNumber = num;
}
public String decodePhoneNumber() {
// Takes string form phone number and decodes based on number pad
// Find code that makes if statement not care about caps
// so if a || b || c number[cnt] = 1 etc..
for (int cnt = 0; cnt < phoneNumber.length(); cnt++) {
char ch1 = phoneNumber.charAt(cnt);
if (Character.ch1.equalsIgnoreCase("a") || ("b") || ("c")) {
} else if (ch1.equalsIgnoreCase("d" || "e" || "f")) {
} else if (ch1.equalsIgnoreCase("j" || "k" || "l")) {
} else if (ch1.equalsIgnoreCase("m" || "n" || "o")) {
} else if (ch1.equalsIgnoreCase("p" || "q" || "r" || "s")) {
} else if (ch1.equalsIgnoreCase("t" || "u" || "v")) {
} else {
}
}
}
}
You have syntax errors and that is why you cannot find ch1.
Try modifying your code as per this syntax. These changes need to be done in all the conditionals.
if ((ch1 == 'a') || (ch1 == 'b') || (ch1 =='c')) {
If you want to make it work regardless of capital letters then you would need to normalize the input to lower case and then do the character comparison:
char ch1 = phoneNumber.toLowerCase().charAt(cnt);
if (ch1 == 'a' || ch1 == 'b' || ch1 == 'c') {
// Do something
}
...
This is the problem: Given a string, count the number of words ending in 'y' or 'z' -- so the 'y' in "heavy" and the 'z' in "fez" count, but not the 'y' in "yellow" (not case sensitive). We'll say that a y or z is at the end of a word if there is not an alphabetic letter immediately following it. (Note: Character.isLetter(char) tests if a char is an alphabetic letter.)
countYZ("fez day") → 2
countYZ("day fez") → 2
countYZ("day fyyyz") → 2
This is my code:
public int countYZ(String str) {
int count = 0;
for (int i=0; i<str.length(); i++){
if (Character.isLetter(i) && (Character.isLetter(i+1)==false || i+1==str.length()) && (Character.toLowerCase(str.charAt(i))=='y' || Character.toLowerCase(str.charAt(i))=='z')){
count++;
}
}
return count;
}
I know it's messy, but I'm just trying to figure out why it's not working right now. It returns "0" each run through. In the if statement, I'm checking for: is i a letter? is i+1 a letter or the end of the string? and finally if i is 'y' or 'z'. Appreciate the help!
You could use a regex:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public int countYZ(String str) {
int count = 0;
Pattern regex = Pattern.compile("[yz](?!\\p{L})", Pattern.CASE_INSENSITIVE);
Matcher regexMatcher = regex.matcher(str);
while (regexMatcher.find()) {
count++;
}
return count;
}
Explanation:
[yz] # Match the letter y or z
(?!\p{L}) # Assert that no letter follows after that
Use split() and endsWith()
public static int countYZ(String str) {
int count = 0;
String temp[] = str.split(" ");
for (int i = 0; i < temp.length; i++) {
if (temp[i].trim().endsWith("y") || temp[i].trim().endsWith("z"))
count++;
}
return count;
}
Output: for all your cases as required
countYZ("fez day") → 2
countYZ("day fez") → 2
countYZ("day fyyyz") → 2
try this fix
for (int i = 0; i < str.length(); i++) {
if ((Character.toLowerCase(str.charAt(i)) == 'y' || Character
.toLowerCase(str.charAt(i)) == 'z')
&& i == str.length() - 1
|| !Character.isLetter(str.charAt(i + 1))) {
count++;
}
}
Try This
public class CountXY {
/**
* #param args
*/
public static int countXY(String str){
int count = 0;
String strSplit[] = str.split(" ");
for(String i:strSplit){
if(i.endsWith("y")||i.endsWith("z")||i.endsWith("Y")||i.endsWith("Z")){
count++;
}
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "Abcy Asdz z z z y y y yyu ZZ Y ";
System.out.println("Count::"+countXY(str));
}
}
public static int countYZ(String str) {
String[] array = str.split("[^a-zA-Z]");
int count = 0;
for (String s : array) {
if (s.toLowerCase().trim().endsWith("y") || s.toLowerCase().trim().endsWith("z"))
count++;
}
return count;
}
Your code is not working because following two conditions
Character.isLetter(i) --> here you are checking isLetter for the i which is int
(Character.isLetter(i+1)==false -> it will cause indexout of error
Please check following I have check its working fine, its just modified version of your code
public class FirstClass {
public static void main(String args[]) {
String string="fez day";
int count = 0;
String[] strcheck = string.split(" ");
for (String str : strcheck) {
if (Character.isLetter(str.charAt(str.length()-1)) &&(Character.toLowerCase(str.charAt(str.length()-1))=='y' || Character.toLowerCase(str.charAt(str.length()-1))=='z')){
count++;
}
}
System.out.println(count);
}
}
Hope this will help, Good Luck
You can try this too
public static void main(String[] args){
System.out.println(countYZ("abcxzy"));
}
public static int countYZ(String str) {
int countYandZ=0;
String[] arr=str.split(" ");
for (String i:arr){
if(("Y".equalsIgnoreCase(String.valueOf(i.charAt(i.length()-1))))||("Z".equalsIgnoreCase(String.valueOf(i.charAt(i.length()-1))))){
countYandZ++;
}
}
return countYandZ;
}
Here's what I've done:
public int countYZ(String str) {
//Initialize a return integer
int ret = 0;
//If it has at least 2 characters, we check both ends to see how many matching instances we have.
if (str.length() >= 2)
{
if (!Character.isLetter(str.charAt(1)) && (str.charAt(0) == 'y' || str.charAt(0) == 'Y' || str.charAt(0) == 'z' || str.charAt(0) == 'Z'))
{
ret++;
}
if (Character.isLetter(str.charAt(str.length() - 2)) && (str.charAt(str.length()-1) == 'y' || str.charAt(str.length()-1) == 'Y' || str.charAt(str.length()-1) == 'z' || str.charAt(str.length()-1) == 'Z'))
{
ret++;
}
}
//If it has more than 3 characters, we check the middle using a for loop.
if (str.length() >= 3)
{
for (int i = 2; i < str.length(); i++)
{
char testOne = str.charAt(i-2);
char testTwo = str.charAt(i-1);
char testThree = str.charAt(i);
//if the first char is a letter, second is a "YZyz" char, and the third is not a letter, we increment ret by 1.
if (Character.isLetter(testOne) && (testTwo == 'y' || testTwo == 'Y' || testTwo == 'z' || testTwo == 'Z') && (!Character.isLetter(testThree)))
{
ret++;
}
}
}
return ret;
}
public int countYZ(String str) {
int count=0;
if ( str.charAt(str.length() - 1) == 'z'||
str.charAt(str.length() - 1) == 'y'||
str.charAt(str.length() - 1) == 'Z'||
str.charAt(str.length() - 1) == 'Y' ) {
count += 1;
}
for (int i = 0; i < str.length(); i++) {
if ( i > 0 ) {
if ( !( Character.isLetter(str.charAt(i)) ) ) {
if ( str.charAt(i - 1) == 'y' ||
str.charAt(i - 1) == 'z' ||
str.charAt(i - 1) == 'Y' ||
str.charAt(i - 1) == 'Z' ) {
count += 1;
}
}
}
}
return count;
}
This allows the words to be separated by anything other than a letter. whitespace, numbers, etc.
public int countYZ(String str) {
int count = 0;
String newStr = str.toLowerCase();
for (int i =0; i < newStr.length(); i++){
if (!Character.isLetter(newStr.charAt(i))){
if (i > 0 && (newStr.charAt(i-1) == 'y' || newStr.charAt(i-1) == 'z'))
count++;
}
}
if (newStr.charAt(str.length()-1) == 'z' || newStr.charAt(str.length()-1) == 'y')
count++;
return count;
}
The method takes in any name and tests whether a character is a vowel or consonant. If it's a vowel, it makes the character uppercase, if it's a consonant, it makes the character lowercase. Any thoughts? I don't know how to add .toUpperCase and .toLowerCase in the if else statements.
public static void parsing(String name[])
{
String temp = name[0];
int i = 0;
for(i = 0; i < temp.length(); i++)
{
if(temp.charAt(i) == 'a' || temp.charAt(i) == 'A' ||
temp.charAt(i) == 'e' || temp.charAt(i) == 'E' ||
temp.charAt(i) == 'i' || temp.charAt(i) == 'I' ||
temp.charAt(i) == 'o' || temp.charAt(i) == 'O' ||
temp.charAt(i) == 'u' || temp.charAt(i) == 'U')
{
System.out.print(temp.charAt(i).toUpperCase);
}//Obviously wrong but I don't know what to do.
else
{
System.out.print(temp.charAt(i).toLowerCase);
}//Obviously wrong but I don't know what to do.
}
To convert a single character use the methods from the Character class:
System.out.print(Character.toUpperCase(temp.charAt(i)));
System.out.print(Character.toLowerCase(temp.charAt(i)));
Create two final arrays - one with the vowels, the second one with the consonants. Then check, whether the current char in the loop is a vowel or consonant and make the appropriate changes.
Your are hitting your head as String is immutable. Rebuild the resulting string.
A (bit suboptimal) solution is:
public static void parsing(String[] names)
{
for (int i = 0; i < names.length; ++i) {
names[i] = chAngEd(names[i]);
}
}
private static String chAngEd(String s) {
String result = "";
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (ch == 'a' || ...) {
ch = Character.toUpperCase(ch);
} else {
ch = ...
}
result += ch;
}
return result;
}
public static void parsing(String names[]){
for (int i=0; i<names.length; ++i){
names[i] = capitaliseConsts(names[i]);
}
}
private static String capitaliseConsts(String name){
StringBuilder sb = new StringBuilder();
Character c;
for (int i=0; i<name.length(); ++i){
c = name.charAt(i);
if (c.equalsIgnoreCase('a') ||
c.equalsIgnoreCase('e') ||
c.equalsIgnoreCase('i') ||
c.equalsIgnoreCase('o') ||
c.equalsIgnoreCase('u')){
sb.append(Character.toUpperCase(c));
}
else{
sb.append(Character.toLowerCase(c));
}
}
return sb.toString();
}
String vowelsArray = "aeiuo";
String constantsArray = "uppercase constants";
int stringLength = name.length();
String givenNameCopy = name.ToString();
for(int i = 0; i < stringLength; i++){
if(vowelsArray.contains(givenNameCopy[i]))
then uppercase
else if(constantsArray.contains(givenNameCopy[i]))
then lowercase
else
continue;
hope this helps.