Austin Jon Magalong
Austin Jon Magalong

Reputation: 21

Java Error; array required, but java.lang.String found

I am currently trying to complete this program and I'm having trouble with this error. I've done many things trying to fix it so I can compile it but it won't work. It seems that the "String alphabet" is getting the error. Can someone help me solve this please?

import java.util.Scanner;
public class Period
{
  private static String phrase;
  private static String alphabet;
  public static void main(String [] args)
  {
    Scanner keyboard = new Scanner(System.in);
    String userInput;
    int[] letter = new int [27];
    int number = keyboard.nextInt();
    System.out.println("Enter a sentence with a period at the end.");
    userInput = keyboard.nextLine();
    userInput.toLowerCase();
  }

  public void Sorter(String newPhrase)
  {
    phrase=newPhrase.substring(0,newPhrase.indexOf("."));
  }

  private int charToInt(char currentLetter)
  {
    int converted=(int)currentLetter-(int)'a';
    return converted;
  }

  private void writeToArray()
  {
    char next;
    for (int i=0;i<phrase.length();i++)
    {
      next=(char)phrase.charAt(i);
      sort(next);
    }
  }

  private String cutPhrase()
  {
    phrase=phrase.substring(0,phrase.indexOf("."));
    return phrase;
  }

  private void sort(char toArray)
  {
    int placement=charToInt(toArray);
    if (placement<0)
    {
      alphabet[26]=1;
    }
    else
    {
      // here is one spot that mainly the error pops up?
      alphabet[placement]=alphabet[placement]+1;
    }
  }

  public void entryPoint()
  {
    writeToArray();
    displaySorted();
  }

  private void displaySorted()
  {
    for (int q=0; q<26;q++)
    {
      System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
    }
  }
}

Upvotes: 0

Views: 1551

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201409

Your sort method is treating alphabet (the String) as an array. String is not a char[] but you can call String.toCharArray() like

private void sort(char toArray)
{
    char[] alpha = alphabet.toLowerCase().toCharArray();
    int placement=charToInt(toArray);
    if (placement<0)
    {
      alpha[26]=1;
    }
    else
    {
      alpha[placement]=alpha[placement]+1;
    }
    alphabet = new String(alpha, "UTF-8");
}

But modifying a String is not possible, because they are immutable. For the same reason your raw call alphabet.toLowerCase() doesn't modify the alphabet in your other method.

Upvotes: 1

Kon
Kon

Reputation: 10810

The variable alphabet is defined as a String data type, but you need to define it as an array if you want to reference it using the bracket notation [] you have in your code. The error message is pretty clear in this case.

String[] example = new String[3];
example[0] = "Hello";
example[1] = "ETC...";

Upvotes: 0

Related Questions