count a certain letter in a type statement.

J

jcsencsits

I am trying to get this to print the number of J's there are in the
users input. and then ask if they want to try again. can someone help
me ecause it doesn't count all lettr J's


import java.util.Scanner;

class countletter
{
public static void main(String[] args) {
int numOfJ = 0;
int control = 1;
int i = 0;
String randomString = " ";
char charLetter;

do {
numOfJ = 0; //j,J

Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
randomString = scan.next();

for (int letter = 0; letter < randomString.length(); letter++) {
charLetter = randomString.charAt(letter);

if (charLetter == 'j' || charLetter == 'J') {
numOfJ++;
} }


System.out.println("\nNo. of 'J' / 'j' = " + numOfJ);

System.out.println(
"If you would like to run the program for another string
please enter 1.");
control = scan.nextInt();
}
while (control == 1);

}
}
 
O

Oliver Wong

I am trying to get this to print the number of J's there are in the
users input. and then ask if they want to try again. can someone help
me ecause it doesn't count all lettr J's
[code snipped]

It works when I test it.

- Oliver
 
J

jcsencsits

Enter a string: jason is jack

No. of 'J' / 'j' = 1
If you would like to run the program for another string please enter 1.
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at countletter.main(Project5B.java:36)

----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.

users input. and then ask if they want to try again. can someone help
me ecause it doesn't count all lettr J's[code snipped]

It works when I test it.

- Oliver
 
G

Gordon Beaton

Enter a string: jason is jack

No. of 'J' / 'j' = 1

You need to read the documentation for Scanner.next().

Doing so might also help you understand why you get the
following exception:
Exception in thread "main" java.util.InputMismatchException

/gordon
 
G

Gordon Beaton

it works for one word but when i do a sentence is when it fails

That was clear from your earlier example. Scanner.next() does not
return the entire line entered by the user, as you seem to expect. Did
you read its documentation as I suggested?

Try displaying the contents of the randomString along with the
corresponding J count.

/gordon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top