kali
kali

Reputation: 21

Produce an output that is the average letter in the string using charAt method and type-casting

I need to create a program that reads in a random word using a prompt.

The program needs to produce an output that is the average letter in the string.

If the average of the letters was 97.2 display a small a, but if the average of the letters was 97.5, display a small b.

I need to use type-casting and the charAt method that is part of the string class

This is all the information that I was given on what I have to do, and I am very confused. I don't have any code, because I don't even know where to start on this question. All help would be greatly appreciated.

Thank you! I really appreciate the feedback!

Here is my code post feedback:

public class Average_Of_String {



public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String word;


    System.out.println("say something");
    word = scan.nextLine();

    float sum = 0;
    for(int i = 0; i < word.length(); i += 1) {
        sum += word.charAt(i);
    }

    System.out.println("Sum is " + sum + " and average is " + Math.round(sum/word.length()) + "(" + sum/word.length() + ")");
    int average = (int) (sum/word.length());
    System.out.println((char) average);
}

}

Upvotes: 1

Views: 64

Answers (2)

Mark
Mark

Reputation: 6404

Try this, code is simple and self-explanatory:

class Average {
  public static void main(String[] args) {
    String word = args[0]; // let us suppose you get the word this way
    float sum = 0;
    for(int i = 0; i < word.length(); i += 1) {
      sum += word.charAt(i);
    }

    System.out.println("Sum is " + sum + " and average is " + Math.round(sum/word.length()) + "(" + sum/word.length() + ")");
  }
}

Upvotes: 1

Mark
Mark

Reputation: 5239

The charAt function returns a character. Ascii Table states:

an ASCII code is the numerical representation of a character such as 'a' or '@' or an action of some sort

On that site you can see that a equals decimal 97 etc.

Upvotes: 1

Related Questions