Reputation: 31
I want to count the number of times a certain character appears in a string, in this case it is the character 'a'. I know I can do this:
import java.util.Scanner;
public class samsJava {
public static void main(String[] args){
String testStr = "StackoverFlow Guess I'll Test The o's";
int counter = 0;
for (int i = 0; i<testStr.length(); i++ ){
if(testStr.charAt(i) == ('o')){
counter++;
}
}
System.out.println("Number of o's:" + counter);
}
}
But what am I doing wrong here:
import java.util.Scanner;
public class samsJava {
public static void main(String[] args){
System.out.println("Enter String:");
Scanner input = new Scanner(System.in);
String inputStr = input.nextLine();
int counterA = 0;
for(int i = 1; i<inputStr.length(); i++){
if(inputStr.substring(i - 1, i).equals('a')){
counterA++;
}
}
System.out.println("number of a's:" + counterA);
}
}
Upvotes: 0
Views: 51
Reputation: 8858
You have to be careful in the for loop:
for (int i = 1; i <= inputStr.length(); i++)
^
or more readable:
for (int i = 0; i < inputStr.length(); i++)
and ...subString(i, i + 1)
Upvotes: 0
Reputation: 201527
No String
will .equals('a')
a char
. You could use .equals("a")
but I'd prefer a for-each
loop like
for(char ch : inputStr.toCharArray()){
if (ch == 'a'){
counterA++;
}
}
Upvotes: 1
Reputation: 44854
substring
is going to return a String
not a char
so change to
if(inputStr.substring(i - 1, i).equals("a")){
Method one is better though.
Upvotes: 1