1

So, I'm new to Java, and am doing an exercise to hone my skills. I'm trying to make a method that takes a string and returns to the user how many of what vowel the string has. This is what I have so far

    static int[] vowelCount(String english)
    {
        int a = 0;
        int e = 0;
        int i = 0;
        int o = 0;
        int u = 0;

        int[] counter = {a, e, i, o, u};

        for (int itt = 0; itt < english.length(); itt++)
        {
            if( english.charAt(itt) == 'a')a++;
            if( english.charAt(itt) == 'e')e++;
            if( english.charAt(itt) == 'i')i++;
            if( english.charAt(itt) == 'o')o++;
            if( english.charAt(itt) == 'u')u++;

        }

        return counter;

    }

    public static void main(String[] args)
    {
        System.out.print(vowelCount("Java rocks!"));

    }

In this instance, I want my output to be {2,0,0,1,0}, but what I get is "[I@15db9742"

Mence
  • 23
  • 3
  • Because printing the array itself gives you its hashcode in Java. [See this question](http://stackoverflow.com/questions/4479683/java-arrays-printing-out-weird-numbers-and-text). – Spencer Wieczorek Apr 09 '17 at 04:12

1 Answers1

0

Firstly you can use Arrays.toString() to print out a visual representation of the array counter.

Secondly it would make more sense to store the position of the vowel in the array like below as currently you are not modifying the array at all i.e. counter looks like [0, 0, 0, 0, 0]:

import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    System.out.print(Arrays.toString(vowelCount("Java rocks!")));
  }

  public static int[] vowelCount(String english) {
    //representing the position in the counter array
    int a = 0; 
    int e = 1; 
    int i = 2;
    int o = 3;
    int u = 4;

    int[] counter = {0, 0, 0, 0, 0}; 

    for (int itt = 0; itt < english.length(); itt++) {
      if( english.charAt(itt) == 'a') counter[a]++;
      if( english.charAt(itt) == 'e') counter[e]++;
      if( english.charAt(itt) == 'i') counter[i]++;
      if( english.charAt(itt) == 'o') counter[o]++;
      if( english.charAt(itt) == 'u') counter[u]++;
    }
    return counter;
  }
}

Output:

[2, 0, 0, 1, 0] 

Try it here!

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40