here you go, as you read whole line you also get return character and you need to get rid of it, there are various way how to do it but as you already use charAt() I used again to just get first (zero position) character in string. this is not bullet prove as somebody can press space and then add character so think about it
import java.util.*;
public class Letter
{
public static void main(String[] args)
{
//needed for scanner class
Scanner kb = new Scanner(System.in);
int charCount = 0;
// get users string
System.out.print("Please enter a string: ");
String userString = kb.nextLine();
// get users character
System.out.print("Please enter a character: ");
char userChar = kb.nextLine().charAt(0);
// tell the user what the program does
System.out.println("\n****This program will return how many times" +
" the character you entered showed up in" +
" the string you entered.****");
for(int i= 0;i<userString.length();i++)
{
if (userString.charAt(i) == userChar)
{
charCount++;
}
}
System.out.println("\nThe specified character " +"\"" + userChar +
"\" is inside the string " + userString +
" " + charCount + " times.\n");
}
} peter_budo
Code tags enforcer
Moderator
15,436 posts since Dec 2004
Reputation Points: 2,806
Solved Threads: 902