user412308 user412308 - 1 month ago 10
Java Question

Java Method to find the occurencies of a certain character

my code should prompt the user to enter a string and a character, and tell where the character is located
for instance
"Welcome" and "e"
returns
"2, 7"

How can my code be fixed? Code is here. Thanks in advance (this is not homework, but some hint could be useful anyway if you don't want to post a solution).

import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Please enter a string and a character");
Scanner input = new Scanner(System.in);
String s = input.nextLine();
char ch = input.next().charAt(0);

System.out.println(count(ch));

}

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

}
}

Answer

Some mistakes:

  1. Your code doesn't compile. Call:

    System.out.println(count(s, ch));
    

    instead of

    System.out.println(count(ch));
    
  2. You count the number of appearances. Instead, you should keep the indexes. You can use a String or you can add them to a list / array and convert it later to what you want.

    public static String count(String s, char a) {
        String result = "";
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == a) {
                result += (i+1) + ", ";
            }
        }
        return result.substring(0, result.length() - 2);
    }
    

    I used i+1 instead of i because the indexes start at 0 in Java.

    I also returned the string result.substring(0, result.length() - 2) without its last 2 characters, because I added , after every character.