Results 1 to 5 of 5
Thread: A java problem for you
- 06-25-2012, 12:46 AM #1
Member
- Join Date
- Feb 2012
- Location
- Phoenix, AZ
- Posts
- 26
- Rep Power
- 0
A java problem for you
Hello,
I wanted to see how others would have solved the following problem.
Create an array of 5 Strings containing people's names. Write a program that counts and displays the total number of vowels in the array.
Here's how I did it.
Java Code:public class Vowels{ public static void main(String[] args){ String[] names = {"Rob", "Tom", "Dad", "Mom", "Sharon"}; int vowelCount = 0; for(int i = 0; i < names.length; i++){ for(int j = 0; j < names[i].length(); j++){ if(names[i].substring(j,j+1).equals("a") || names[i].substring(j,j+1).equals("e") || names[i].substring(j,j+1).equals("i") || names[i].substring(j,j+1).equals("o") || names[i].substring(j,j+1).equals("u")) vowelCount = vowelCount + 1; /*System.out.println(names[i].substring(j,j+1));*/ } } System.out.println(vowelCount); } }
- 06-25-2012, 02:41 AM #2
Re: A java problem for you
Please go through the Forum Rules -- particularly the third paragraph.
dbIf you're forever cleaning cobwebs, it's time to get rid of the spiders.
- 06-25-2012, 02:50 AM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 19
Re: A java problem for you
I'd use charAt() and the expressive idiom "whatever".indexOf(someChar). Both are String methods.
I'd also ask for clarification from whoever posed the problem concerning what to do with aunty Yvonne, cousin Jenny et al. (Although Al isn't really controversial.)Last edited by pbrockway2; 06-25-2012 at 02:55 AM.
- 06-25-2012, 03:50 AM #4
Re: A java problem for you
You do this 6 times
names[i].substring(j,j+1)
vs one time and use the results.
Indexing and substring are expensive and the repeated use of expressions leaves lots of room for coding errors.If you don't understand my response, don't ignore it, ask a question.
- 06-25-2012, 11:33 AM #5
Banned
- Join Date
- Jun 2012
- Location
- Beijing,China
- Posts
- 34
- Rep Power
- 0
Re: A java problem for you
How about this:
Java Code:import java.util.Arrays; public class JavaApplication23 { public static void main(String[] args){ String[] names = {"Rob", "Tom", "Dad", "Mom", "Sharon"}; int x=Arrays.toString(names).replaceAll("[^aAeEiIoOuU]","").length(); System.out.println(x); } }
Similar Threads
-
Problem with Java Web Applications and Java in Control Panel
By Abysinian in forum Advanced JavaReplies: 4Last Post: 03-16-2012, 12:29 PM -
Small problem with problem with Java, C++ parse program.
By dragstang86 in forum New To JavaReplies: 4Last Post: 10-30-2011, 04:43 AM -
Help! Java Problem!!
By TheBreakdown in forum New To JavaReplies: 2Last Post: 08-04-2011, 10:06 AM -
Problem Display Jmenubar Java Se6 u23 versus Java SE6 u22
By Ravanelly in forum Advanced JavaReplies: 0Last Post: 01-07-2011, 10:36 AM -
JAVA and XML Problem
By jackchang in forum XMLReplies: 4Last Post: 02-22-2009, 09:28 PM
Bookmarks