You are defining "count" in your main method as int.
But you also have a method called "count". This is bad practice and this is why it does not do what you expect. Always use different names!
You are assigning to your variable "count" the length of your input string (why?), but you are not calling your method "count", which would have brought back the desired number of letters "i" inside your input string.
This code does not look as if you have written it your own.
It looks as if someone has intentionally modified working code for some students to correct it. The students should understand the difference between
method and variable and between variable "i" and character "i". If they understand, they are able to correct the code.
If I am right, then helping you here may have negative influence to your learn success and wasting my time. Your teacher is paid for explaining you all things, whereas posting such code here prohibits me from helping people who really need help with their own code.
I need to count the number of letters in a string, disregarding case. It needs to use these two methods. What's wrong?
- import java.util.Scanner;
-
-
public class CountLetters
-
{
-
public static void main(String[] args)
-
{
-
Scanner input;
-
-
input = new java.util.Scanner(System.in);
-
-
String s;
-
int count = 0;
-
-
-
System.out.print( "Enter a string: " );
-
s = input.nextLine();
-
count = s.length();
-
-
-
System.out.println("The number of letters in the string is " +count+".");
-
}
-
public static int count (String s)
-
{
-
int count = 0;
-
count = s.length();
-
for(int i = 0; i < s.length(); i++) {
-
if(s.charAt(i) == 'i')
-
{
-
count++;
-
}
-
}}}