Count y and z at end of a word - java

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;
}

Related

How do I handle punctuation in this Pig Latin translator?

The rest of the code is working perfectly but I cannot figure out how to prevent punctuation from being translated.
public class PigLatintranslator
{
public static String translateWord (String word)
{
String lowerCaseWord = word.toLowerCase ();
int pos = -1;
char ch;
for (int i = 0 ; i < lowerCaseWord.length () ; i++)
{
ch = lowerCaseWord.charAt (i);
if (isVowel (ch))
{
pos = i;
break;
}
}
if (pos == 0 && lowerCaseWord.length () != 1) //translates if word starts with vowel
{
return lowerCaseWord + "way"; // Adding "way" to the end of string
}
else if (lowerCaseWord.length () == 1) //Ignores words that are only 1 character
{
return lowerCaseWord;
}
else if (lowerCaseWord.charAt(0) == 'q' && lowerCaseWord.charAt(1) == 'u')//words that start with qu
{
String a = lowerCaseWord.substring (2);
return a + "qu" + "ay";
}
else
{
String a = lowerCaseWord.substring (1);
String b = lowerCaseWord.substring (0,1);
return a + b + "ay"; // Adding "ay" at the end of the extracted words after joining them.
}
}
public static boolean isVowel (char ch) checks for vowel
{
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y')
{
return true;
}
return false;
}
}
I need the translation to ignore punctuation. For example "Question?" should be translated to "estionquay?" (question mark still in the same position and not translated)
As Andreas said, if the function is expecting only one word, it should be the responsibility of the calling function to ensure there's no full sentence or punctuation being passed to it. With that said, if you require the translator to handle this, you need to find the index of the string where the punctuation or non-letter character occurs. I added in a main method to test the function:
public static void main(String[] args) {
System.out.println(translateWord("QUESTION?"));
}
I added a loop into the qu case to find the punctuation being input, the two checks are to see if the character at position i is inside the range of a - z. The sub-string then only goes to the point where the punctuation is found.
int i;
for (i = 0; i < lowerCaseWord.length(); i++) {
if(lowerCaseWord.charAt(i) > 'z' || lowerCaseWord.charAt(i) < 'a') {
break;
}
}
String a = lowerCaseWord.substring (2, i);
String b = lowerCaseWord.substring(i);
return a + "qu" + "ay" + b;
This may need some tweaking if you're worried about words with hyphens and whatnot but this should put across the basic idea.
Here's the output I received:
$javac PigLatintranslator.java
$java -Xmx128M -Xms16M PigLatintranslator
estionquay?

Java-How to translate a String to piglatin?

I am writing a pig latin code and I am tripped up by how to get my program to identify where the next vowel in the word is if the first letter in the word is a consonant. Then it moves the first part of the word, up to the first vowel, to the end of the word and prints ay along with it. (ex. trees = eestray)
This is the code I have now
// word is bringing in the string entered from the user
public static void translate(String word) {
String wordCap, pigLatin = "";
char vowels;
int lowest = 0, tempOne, tempTwo, tempThree, tempFour, tempFive;
wordCap = word.toUpperCase();
vowels = wordCap.charAt(0);
if (vowels == 'A' || vowels == 'E' || vowels == 'I' || vowels == 'O' || vowels == 'U') {
word = word + "way";
System.out.println(word);
}
else {
tempOne = wordCap.indexOf('A', 1);
if (lowest > tempOne && tempOne != -1) {
lowest = tempOne;
}
tempTwo = wordCap.indexOf('E', 1);
if (lowest > tempTwo && tempTwo != -1) {
lowest = tempTwo;
}
tempThree = wordCap.indexOf('I', 1);
if (lowest > tempThree && tempThree != -1) {
lowest = tempThree;
}
tempFour = wordCap.indexOf('O', 1);
if (lowest > tempFour && tempFour != -1) {
lowest = tempFour;
}
tempFive = wordCap.indexOf('U', 1);
if (lowest > tempFive && tempFive != -1) {
lowest = tempFive;
}
public static char vowel(String word) {
int start= 0, end= 0;
char vowels;
for (int i = 0; i < word.length(); i++) {
vowels = word.charAt(i);
if (vowels == 'A' || vowels == 'E' || vowels == 'I' || vowels == 'O' || vowels == 'U') {
end = i;
break;
}
}
return (char) end;
}
(in translate method)
for (int i = 0; i<wordCap.length(); i++) {
if (vowel(wordCap.charAt(i))) {
vowels = wordCap.charAt(i);
}
}
The problem now is that the vowel method is not an applicable method type. It says it must be a char?
Let me try to shorten that method for you ;)
Try something like this:
private static final char[] vowels = {'a', 'e', 'i', 'o', 'u'};
public static String translate(String word) {
int start = 0; // start index of word
int firstVowel = 0;
int end = word.length(); // end index of word
for(int i = 0; i < end; i++) { // loop over length of word
char c = Character.toLowerCase(word.charAt(i)); // char of word at i, lower cased
if(Arrays.asList(vowels).contains(c)) { // convert vowels to a list so we can use List.contains() convenience method.
firstVowel = i;
break; // stop looping
}
}
if(start != firstVowel) { // if start is not equal to firstVowel, we caught a vowel.
String startString = word.substring(firstVowel, end);
String endString = word.substring(start, firstVowel) + "ay";
return startString+endString;
}
return word; //couldn't find a vowel, return original
}
What this snippet does, is iterate over every character in the word, storing the index of the first vowel in the firstVowel variable. Then, we get every character from firstVowel to end; and store it in startString. Then, we get every character from start to firstVowel; add "ay", and store it in endString. Finally, we concatenate these strings together and return them, resulting in the desired output.
We can test this with System.out.println(translate("trees"));
EDIT: Without array, as requested:
public static String translate(String word) {
char a = 'a';
char e = 'e';
char i = 'i';
char o = 'o';
char u = 'u';
int start = 0;
int firstVowel = 0;
int end = word.length();
for(int i = 0; i < end; i++) {
char c = Character.toLowerCase(word.charAt(i));
if(c == a || c == e || c == i || c == o || c == u) {
firstVowel = i;
break;
}
}
if(start != firstVowel) {
String startString = word.subString(firstVowel, end);
String endString = word.subString(start, firstVowel) + "ay";
return startString+endString;
}
return word;
}
As you can see, arrays shorten things up quite a bit!
If you're feeling pedantic about the Arrays.asList().contains() call, we could define our own:
public static boolean containsChar(char[] lookIn, char lookFor) {
boolean doesContainChar = false;
for(char c : lookIn) {
if(doesContainChar = c == lookFor)
break;
}
return doesContainChar;
}
You might want to use a for loop to iterate through the letters of each word until it finds a vowel. Example:
String wordCap = word.toUpperCase();
char vowels;
for (int i=0; i<wordCap.length(); i++) {
if (isVowel(wordCap.charAt(i))) {
vowels = wordCap.charAt(i);
break;
}
}
Of course, I only used isVowel() for the sake of keeping the example concise. You'll have to identify it as a vowel the same way you did in your first if statement (or write an isVowel() method yourself).
For modifying the word, you'll also want to declare a variable to hold the index of the vowel. The previous section of code could be added to for this, like so:
String wordCap = word.toUpperCase();
char vowels;
int vowelIndex;
String newWord;
for (int i=0; i<wordCap.length(); i++) {
if (isVowel(wordCap.charAt(i))) {
vowels = wordCap.charAt(i);
vowelIndex = i;
break;
}
}
Then you could reference vowelIndex when modifying the word.
if (vowelIndex == 0) {
newWord = word + "way";
} else {
newWord = word.substring(vowelIndex) + word.substring(0, vowelIndex) + "ay";
}
return word;

How to replace a char in a string without using Replace() in Java?

I've been having trouble with this assignment:
Given a string, replace the first occurrence of 'a' with "x", the second occurrence of 'a' with "xx" and the third occurrence of 'a' with "xxx". After the third occurrence, begin the replacement pattern over again with "x", "xx", "xxx"...etc.; however, if an 'a' is followed by more than 2 other 'a' characters in a row, then do not replace any more 'a' characters after that 'a'.
No use of the replace method is allowed.
aTo123X("ababba") → "xbxxbbxxx"
aTo123X("anaceeacdabnanbag") → "xnxxceexxxcdxbnxxnbxxxg"
aTo123X("aabaaaavfaajaaj") → "xxxbxxxaaavfaajaaj"
aTo123X("pakaaajaaaamnbaa") → "pxkxxxxxxjxxaaamnbaa"
aTo123X("aaaak") → "xaaak"
My code's output is with a's included, x's added but not the correct amount of x's.
public String aTo123X(String str) {
/*
Strategy:
get string length of the code, and create a for loop in order to find each individual part of the String chars.check for a values in string and take in pos of the a.
if one of the characters is a
replace with 1 x, however, there aren't more than 2 a's immediately following first a and as it keeps searching through the index, add more x's to the original string, but set x value back to 1 when x reaches 3.
if one of characters isn't a,
leave as is and continue string.
*/
String xVal = "";
String x = "x";
String output = "";
for (int i = 0; i < str.length(); i++){
if( str.charAt(i) == 'a'){
output += x;
str.substring(i+1, str.length());
}
output += str.charAt(i);
}
return output;
}
This is the code that does the same. I've commented the code to explain what it does
public class ReplaceChar {
public static void main(String... args){
String[] input =new String[]{"ababba","anaceeacdabnanbag","aabaaaavfaajaaj"};
StringBuilder result = new StringBuilder();
for (int i= 0; i < input.length;i++){
result.append(getReplacedA(input[i]));
result.append("\n");
}
System.out.println(result);
}
private static String getReplacedA(String withA){
// stringBuilder for result
StringBuilder replacedString = new StringBuilder();
// counting the number of time char 'a' occurred in String for replacement before row of 'aaa'
int charACount = 0;
// get the first index at which more than two 'aa' occurred in a row
int firstIndexOfAAA = withA.indexOf("aaa") + 1;
// if 'aaa' not occurred no need to add the rest substring
boolean addSubRequired = false;
// if the index is 0 continue till end
if (firstIndexOfAAA == 0)
firstIndexOfAAA = withA.length();
else
addSubRequired = true;
char[] charString = withA.toCharArray();
//Replace character String[] array
String[] replace = new String[]{"x","xx","xxx"};
for(int i = 0; i < firstIndexOfAAA; i++){
if (charString[i] == 'a'){
charACount++;
charACount = charACount > 3 ? 1 : charACount ;
// add the number x based on charCount
replacedString.append(replace[charACount - 1]);
}else{
replacedString.append(charString[i]);
}
}
// if the String 'aaa' has been found previously add the remaining subString
// after that index
if (addSubRequired)
replacedString.append(withA.substring(firstIndexOfAAA));
// return the result
return replacedString.toString();
}
}
Output:
xbxxbbxxx
xnxxceexxxcdxbnxxnbxxxg
xxxbxxxaaavfaajaaj
EDIT : Some Improvement You can make for some corner cases in the getReplacedA() function:
Check if char 'a' is there or not in the String if not just return the String No need to do anything further.
Use IgnoreCase to avoid the uppercase or lowercase possibility.
Firstly, string is immutable, so the below statement does nothing
str.substring(i+1, str.length());
I guess you wanted to do:
str = str.substring(i+1, str.length());
However, even after fix that, your program still doesn't work. I can't really comprehend your solution. 1) you are not detecting more than 3 a's in a row. 2) you are not appending "xx" or "xxx" at all
Here is my version, works for me so far:
public static void main(String[] args) {
System.out.println(aTo123X("ababba")); // "xbxxbbxxx"
System.out.println(aTo123X("anaceeacdabnanbag")); // "xnxxceexxxcdxbnxxnbxxxg"
System.out.println(aTo123X("aabaaaavfaajaaj")); // "xxxbxxxaaavfaajaaj"
}
public static String aTo123X(String str) {
String output = "";
int aOccurrence = 0;
String[] xs = {"x", "xx", "xxx"};
for (int i = 0; i < str.length(); ++i) {
if (str.charAt(i) == 'a') {
output += xs[aOccurrence % 3]; // append the x's depending on the number of a's we have seen, modulus 3 so that it forms a cycle of 3
if (i < str.length() - 3 && str.charAt(i + 1) == 'a' && str.charAt(i + 2) == 'a' && str.charAt(i + 3) == 'a') {//if an 'a' is followed by more than 2 other 'a' characters in a row
output += str.substring(i + 1);
break;
} else {
++aOccurrence; // increment the a's we have encountered so far
}
} else {
output += str.charAt(i); // append the character if it is not a
}
}
return output;
}
public class NewClass {
public static void main(String[] args) {
System.out.println(aTo123X("ababba")); // "xbxxbbxxx"
System.out.println(aTo123X("anaceeacdabnanbag")); // "xnxxceexxxcdxbnxxnbxxxg"
System.out.println(aTo123X("aabaaaavfaajaaj")); //xxxbxxxaaavfaajaaj
}
public static String aTo123X(String str) {
String output = "";
int aCount = 0;
int inRow = 0;
for (int i = 0; i < str.length();) {
if (str.charAt(i) == 'a') {
if (inRow <= 1) {
inRow++;
aCount++;
if (aCount == 1) {
output += "x";
} else if (aCount == 2) {
output += "xx";
} else {
output += "xxx";
aCount = 0;
}
boolean multiple = ((i + 1) < str.length()) && (str.charAt(i + 1) == 'a')
&& ((i + 2) < str.length()) && (str.charAt(i + 2) == 'a');
if (multiple) {
i++;
while (i < str.length()) {
output += str.charAt(i++);
}
return output;
}
} else {
output += str.charAt(i);
}
} else {
output += str.charAt(i);
inRow = 0;
}
i++;
}
return output;
}
}
I am pointing out problems in your code in form of comments in the code itself.
public String aTo123X(String str) {
//You are not using xVal variable in your code, hence it's obsolete
String xVal = "";
//You don't need x variable as you can simply use string concatenation
String x = "x";
String output = "";
for (int i = 0; i < str.length(); i++) {
/**
* Here, in "if" block you have not implmented any logic to replace the 2nd and
* 3rd occurence of 'a' with 'xx' and 'xxx' respectively. Also, substring() returns
* the sub-string of a string but you are not accepting that string anywhere, and
* you need not even use sub-string as "for" loop will cycle through all the
* characters in the string. If use sub-string method you code will only process
* alternative characters.
*/
if( str.charAt(i) == 'a') {
output += x;
str.substring(i+1, str.length());
}
/**
* Because of this statement a's are also returned, because this statement gets
* in both scenarios, whether the current character of string is a or not.
* But, this statement should get executed only when current character of the
* string is 'a'. So, in terms of coding this statement gets executed no matter
* "if" loop is executed or not, but it should get executed only when "if" loop
* is not executed. So, place this statement in else block.
*/
output += str.charAt(i);
}
return output;
}
I have implemented the logic for you. Here is Solution for your problem, just copy and run it. It passes all the specified test cases.
public String aTo123X(String str) {
String output = "";
int count = 1;
boolean flag = true;
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == 'a' && flag == true) {
switch(count) {
case 1: output += "x";
count++;
break;
case 2: output += "xx";
count++;
break;
case 3: output += "xxx";
count = 1;
break;
}
if ((str.charAt(i+1) == 'a' && str.charAt(i+2) == 'a') == true) {
flag = false;
}
}
else {
output += str.charAt(i);
}
}
return output;
}
I use Map To store where to replace
public static void main(String[] args) {
System.out.println(aTo123X("ababba"));//xbxxbbxxx
System.out.println(aTo123X("anaceeacdabnanbag"));//xnxxceexxxcdxbnxxnbxxxg
System.out.println(aTo123X("aabaaaavfaajaaj"));//xxxbxxxaaavfaajaaj
}
public static String aTo123X(String str){
String res = "";
int nthReplace = 1; //Integer to store the nth occurence to replace
//Map to store [key == position of 'a' to replace]
//[value == x or xx or xxx]
Map<Integer, String> toReplacePos = new HashMap<>();
//The loop to know which 'a' to replace
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == 'a'){
toReplacePos.put(i, nthReplace % 3 == 1 ? "x": (nthReplace % 3 == 2 ? "xx": "xxx"));
nthReplace++;
//Break if an 'a' is followed by more than 2 other 'a'
try {
if((str.charAt(i+1) == 'a')
&& (str.charAt(i+2) == 'a')
&& (str.charAt(i+3) == 'a')){
break;
}
} catch (StringIndexOutOfBoundsException e) {
}
}
}
//Do the replace
for (int i = 0; i < str.length(); i++) {
res += toReplacePos.containsKey(i) ? toReplacePos.get(i) : str.charAt(i);
}
return res;
}
I have edited my answer. This one is giving the correct solution:
public static void main (String[] args) throws InterruptedException, IOException, JSONException {
System.out.println(aTo123X("ababba")); //xbxxbbxxx
System.out.println(aTo123X("anaceeacdabnanbag")); //xnxxceexxxcdxbnxxnbxxxg
System.out.println(aTo123X("aabaaaavfaajaaj")); //xxxbxxxaaavfaajaaj
}
public static String aTo123X(String str) {
String x = "x";
String xx = "xx";
String xxx = "xxx";
int a = 1;
int brek = 0;
String output = "";
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == 'a' && a == 1) {
output += x;
str.substring(i+1, str.length());
a = 2;
try {
if(str.charAt(i+1) == 'a' && str.charAt(i+2) == 'a')
brek += 1;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(str.charAt(i) == 'a' && a == 2) {
output += xx;
str.substring(i+1, str.length());
a = 3;
try {
if(str.charAt(i+1) == 'a' && str.charAt(i+2) == 'a')
brek += 1;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(str.charAt(i) == 'a' && a == 3) {
output += xxx;
str.substring(i+1, str.length());
a = 1;
try {
if(str.charAt(i+1) == 'a' && str.charAt(i+2) == 'a')
brek += 1;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
output += str.charAt(i);
brek = 0;
}
if(brek>0) {
output += str.substring(i+1);
break;
}
}
return output;
}

"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range"

Here is the problem: Return true if the string "cat" and "dog" appear the same number of times in the given string. Examples: catDog("catdog") → true; catDog("catcat") → false; catDog("1cat1cadodog") → true
public boolean catDog(String str) {
int countCat=0;
int countDog=0;
for (int i=0; i<str.length();i++)
{
if (str.charAt(i)== 'c'&& str.length()>=3)
{
if (str.substring(i,i+3).equals("cat"))
countCat++;
}
}
for (int i=0; i<str.length();i++)
{
if (str.charAt(i)== 'd' && str.length()>=3)
{
if (str.substring(i,i+3).equals("dog"))
countDog++;
}
}
if (countCat == countDog)
return true;
else
return false;
}
In your for loops conditions you are checking if entire String has length greater or equal 3 instead of checking only part from i till end. Try maybe with
str.length() - i >= 3
instead of
str.length() >= 3
str.substring(i,i+3).equals("cat")
i might be the last and i+3 will give an error
Why don't you simply use StringUtils#countMatches?
StringUtils.countMatches(myStr, "cat") == StringUtils.countMatches(myStr, "dog");
Don't get lost with the indexes. However, if you don't want to use this method, debugging your code is the best thing you can do.
Okay, this is what I might do:
The problem was with your check str.length() >= 3. It should have been i + str.length().
I also suggest some changes to your code to get rid of duplication. Here I extracted the part that counts the number of appearances of a substring and moved it to its own method. The part that checks if count of cat equals count of dog now calls said method twice.
public static void main(String[] args) {
System.out.println(catDog("catdog"));
System.out.println(catDog("catcat"));
System.out.println(catDog("1cat1cadodog"));
System.out.println(catDog("catdogcatc"));//Would previously throw error.
}
public static boolean catDog(String str) {
int countCat = countAppearances(str, "cat");
int countDog = countAppearances(str, "dog");
return countCat == countDog;
}
private static int countAppearances(String str, String key) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == key.charAt(0) && i + key.length() <= str.length()) {
if (str.substring(i, i + key.length()).equals(key)) {
count++;
}
}
}
return count;
}
You need to update your first condition before spiting you string like:
if (str.charAt(i)== 'c' && (str.length() - i) >= 3)
{
if (str.substring(i,i+3).equals("cat"))
countCat++;
}
public boolean catDog(String str) {
int catCount = 0, dogCount = 0;
//run a for loop to check cat count
//run loop till 2nd last character
for (int i = 0; i < str.length() - 2; i++) {
//now check if the charaters at positions matches "cat"
//if matches then increment cat count
if (str.charAt(i) == 'c' && str.charAt(i + 1) == 'a' && str.charAt(i + 2) == 't') {
catCount++;
} else if (str.charAt(i) == 'd' && str.charAt(i + 1) == 'o' && str.charAt(i + 2) == 'g') {
//else check if the charaters at positions matches "dog"
//if matches then increment dog count
dogCount++;
}
}
//check cat count and dog count
if (catCount == dogCount) {
return true;
} else {
return false;
}
}

Java - Converting the characters in a string array depending on whether or not it's a vowel

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.

Categories

Resources