简体   繁体   中英

Java - Using a method to populate and print Arrays for number of each letter in a String

I have the following code, that I think should work, but in the println am getting the error message:

Multiple markers at this line:

  • The method letterFrequencies(String) in the type LetterFrequencies is not applicable for the arguments ()

  • input cannot be resolved to a variable

'public class LetterFrequencies {'

public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        String str = "I love programming ";

        System.out.println (letterFrequencies(input));
    }

    public static int timesCharOccurs (String str, char character) 
    {
        int timesOccurs = 0;

        String str2 = str.toLowerCase();
        char [] charArray = str2.toCharArray();  // Turns the String into Char
        for (int i=0; i<str2.length(); i++)   // Loops for the number of Chars as transformed
        {
            if (charArray[i] == character) 
            {
                timesOccurs ++;
            }
        }
        return timesOccurs;
    }

    public int[] letterFrequencies (String input)
    {
        int [] occuranceValues = new int[26];
        char [] alphabetArray = {
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

        for (int i=0; i < alphabetArray.length; i++)
        {
            char letter = alphabetArray[i];
            occuranceValues[i] = timesCharOccurs(input, letter);
        }
        return occuranceValues;
    }

What I think should be happening is the print line should return the array in the letterFrequencies method, but cannot seem to get it accepted

I am doing it this particular way as it is a problem from my Java Lab.

appreciate any help

Your variable in main is named str (not input ). Change

System.out.println (letterFrequencies(input));

to

System.out.println (Arrays.toString(letterFrequencies(str)));

or

String input = "I love programming ";
System.out.println(Arrays.toString(letterFrequencies(input)));

And I get

[1, 0, 0, 0, 1, 0, 2, 0, 2, 0, 0, 1, 2, 1, 2, 1, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM