-2

My goal is to write a program to determine the frequency of characters in a char[]. The test case for my program is written below:

Expected:

Enter a string: Welcome to Java
Enter a character: ee
appears 2 times

Actual:

Enter a string: Welcome to Java
Enter a character: ee
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 0

My attempt

package Recursion;
import java.util.Arrays;
import java.util.Scanner;

public class Test15 {

    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        char[] characterArray    = input.nextLine().toCharArray();
        System.out.print("Enter a character: ");
        char character = input.nextLine().toCharArray()[0];
        System.out.printf("appears %d times",count(characterArray, character));
    }

    //input: list of characters
    //output: display frequency of characters in the list
    public static int count(char[] chars, char ch){
        int high = 0;
        return count(chars, ch, high);
    }

    public static int count(char[] chars, char ch, int high){
        if(chars[chars.length-1] == ch)
            high++;
        
        if(chars.length == 0)
            return 0;

        return count(Arrays.copyOfRange(chars, 0, chars.length - 1), ch, high);
    }
}

halfer
  • 19,824
  • 17
  • 99
  • 186
Evan Gertis
  • 1,796
  • 2
  • 25
  • 59

1 Answers1

-1
package Recursion;
import java.util.Arrays;
/*
    name: Evan Getis
    date: 03/31
    program: sum of digits
*/
import java.util.Scanner;

public class Test15 {

    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        char[] characterArray    = input.nextLine().toCharArray();
        System.out.print("Enter a character: ");
        char character = input.nextLine().toCharArray()[0];
        System.out.printf("appears %d times",count(characterArray, character));
    }

    //input: list of characters
    //output: display frequency of characters in the list
    public static int count(char[] chars, char ch){
        int high = 0;
        return count(chars, ch, high);
    }

    public static int count(char[] chars, char ch, int high){
        if(chars.length == 0)
            return high;

        if(chars[chars.length-1] == ch)
            high++;

        return count(Arrays.copyOfRange(chars, 0, chars.length - 1), ch, high);
    }
}
Evan Gertis
  • 1,796
  • 2
  • 25
  • 59