|
Re: Help with a basic JAVA program for class-
|
Posted: Oct 20, 2005 7:34 PM
|
|
There are three changes: 1. For your exception: use < instead of <= in for loop condition. The changed for loop is:
for (int letter = 0; letter < randomString.length(); letter++) {
// your same code goes here
}
2. In case user wants to start the program again by typing1, you need to reinitialize all characters count to zero. I placed that code just after do { ...
3. You had some messed up braces at the end of while(control == 1 ) ... I fixed that one too.
So, here is you working code.
package test;
import java.util.Scanner;
class Project5B {
public static void main(String[] args) {
//1. Set up all variables(set some values of the variables)
// These variables are moved inside do-while loop so that if
// user wants to start over by typing 1 then all of these values
// are reinitialized to zero
int numOfA = 0; //a,A
int numOfE = 0; //e,E
int numOfI = 0; //i,I
int numOfO = 0; //o,O
int numOfU = 0; //u,U
int numOfOther = 0; //other characters
int control = 1; //control is the variable used with the while loop
int i = 0; //i is the variable used to count in the char.At if statement
String randomString = " "; //user input string
char charLetter; //sets up the char for the for and nested ifs
//2. Set up the loop for user end function
do {
numOfA = 0; //a,A
numOfE = 0; //e,E
numOfI = 0; //i,I
numOfO = 0; //o,O
numOfU = 0; //u,U
numOfOther = 0; //other characters
//3. Set up the scanner and scan the string from user
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
randomString = scan.next();
//4. Determine the various information about the string
for (int letter = 0; letter < randomString.length(); letter++) {
charLetter = randomString.charAt(letter);
if (charLetter == 'a' || charLetter == 'A') {
numOfA++;
}
else if (charLetter == 'e' || charLetter == 'E') {
numOfE++;
}
else if (charLetter == 'i' || charLetter == 'I') {
numOfI++;
}
else if (charLetter == 'o' || charLetter == 'O') {
numOfO++;
}
else if (charLetter == 'u' || charLetter == 'U') {
numOfU++;
}
else {
numOfOther++;
}
}
//5. Print that which was determined
System.out.println("\nNo. of 'A' / 'a' = " + numOfA);
System.out.println("No. of 'E' / 'e' = " + numOfE);
System.out.println("No. of 'I' / 'i' = " + numOfI);
System.out.println("No. of 'O' / 'o' = " + numOfO);
System.out.println("No. of 'U' / 'u' = " + numOfU);
System.out.println("No. of non-vowels = " + numOfOther);
//6. Scan for the user end function interger
System.out.println(
"If you would like to run the program for another string please enter 1.");
control = scan.nextInt();
}
while (control == 1);
// {
// ;
//}
}
}
|
|