Question:
Java String Array program?
Rocket
2012-04-07 06:35:07 UTC
Write a static method named vowelCount that accepts a String as a parameter and produces and returns an array of integers representing the counts of each vowel in the String.
The array returned by your method should hold 5 elements: the first is the count of As, the second is the count of Es, the third is the count of Is, the fourth is the count of Os, and the fifth is the count of Us.
You may assume that the string contains no uppercase letters.
For example, the call of vowelCount("black banana republic boots") should return an array containing {4, 1, 1, 2, 1}.

This is what I got so far:
import java.util.*;
public class Vowel {
public static void main(String[] args) {
vowelCount(text);
}

public static int[] vowelCount(String text) {
int[] counts = new int[5];
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == 'a') {
counts[0]++;
} else if (c == 'e') {
counts[1]++;
} else if (c == 'i') {
counts[2]++;
} else if (c == 'o') {
counts[3]++;
} else if (c == 'u') {
counts[4]++;
}
}
return counts;
}
}

Any help please and thanks!
Three answers:
AnalProgrammer
2012-04-07 07:05:37 UTC
//No import statement is needed in this example.

public class VowelCountProject {



public static void main(String[] args) {

// TODO code application logic here

String data = "black banana republic boots";

int[] result;

result = vowelCount(data);

System.out.print("{");

for (int i = 0; i < result.length; i++) {

if (i == 0) {

System.out.print(result[i]);

} else {

System.out.print(", " + result[i]);

}

}

System.out.println("}");

}



public static int[] vowelCount(String input) {

int[] vowelCountArray = new int[5];

String vowel = "aeiou";



for (int i = 0; i < input.length(); i++) {

int j = vowel.indexOf(input.charAt(i));

if (j < 0) {

} else {

vowelCountArray[j]++;

}

}

return vowelCountArray;

}

}



Have fun.
Dopli
2012-04-07 07:05:55 UTC
Skimming through what you've got it seems ok, what error message are you getting?



Also, instead of using if else, look up something called a switch case.

You can replace the chunk of code from "if (c=='a')....counts[4]++;" to



switch(c){



case('a'): counts[0]++; break;

case('b'): counts[1]++; break;

//same with c, d and e

}



It'll make the code look a lot neater.
Lutty
2016-02-24 02:17:58 UTC
if you want to iterate through the whole array for(i=0; i < stra.length; i++) { if (stra[i] != null) System.out.print(" Not Empty") else System.out.print("Empty") }


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...