问题描述:

Here is my code:

public class Exercixe09_04 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Enter a string: ");

String s1 = input.next();

System.out.println("Enter a character: ");

String s2 = input.next();

char c = s2.charAt(0);

int num = count(s1, c);

System.out.print(num);

}

public static int count(String str, char a)

{

int count = 0;

for(int i =0; i < str.length(); i++)

if(str.charAt(i) == 'a'){

count++;

}

return count;

}

}

When I compile and run it, nothing prints. Can someone please help me figure out what is wrong?

网友答案:
import java.util.Scanner;

public class Exercixe09_04 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String s1 = input.next();
        System.out.print("Enter a character: ");
        String s2 = input.next();

        char c = s2.charAt(0);

        int num = count(s1, c);

        System.out.println(num);
    }

    public static int count(String str, char a) {
        int count = 0;
        for (int i = 0; i < str.length(); i++)
            if (str.charAt(i) == a) {
                count++;
            }

        return count;
    }
}

Sample run:

[email protected]:/tmp$ java Exercixe09_04
Enter a string: Hello
Enter a character: l
2
相关阅读:
Top