How to Calculate Your Scrabble Score in Java

Calculating a Scrabble score in Java involves scoring points based on the words used, and applying any word modifiers. The most important aspect is using the proper data structure to hold the point values of any letters, and having that structure available to pull the proper point values. By using a HashMap to store pairs of letter-point values, you can build a simple Scrabble points calculator.

Things You'll Need

  • Java Development Kit (JDK)
  • Interactive Development Environment (IDE)
Show More

Instructions

    • 1

      Set up your calculation class:

      import java.utils.*

      class ScrabbleWord{

      public static void main(String[] args){

      }

      }

    • 2

      Create a HashMap inside the main function to store letter values. A HashMap stores values in key-value pairs. In this case, this will be the letter and its Scrabble point value:

      Map<String, Integer> letters = new HashMap<String, Integer>();

      letters.put("a", new Integer(1));
      letters.put("b", new Integer(3));
      /*...through the alphabet*/
      letters.put("z", new Integer(10));

    • 3

      Read the arguments of the program. In this example, the first argument of the program should represent the word to calculate, and is required. The second argument denotes if you have a double- or triple-word score with either the character "D" or "T." The second argument is optiona:l

      String word = args[0];

      if (args.length > 0){
      char score = args[1];
      }

    • 4

      Calculate the score of the word. Run a "for" loop over the words in the string and use the scoring dictionary to calculate the score:

      int i = 0;
      int points = 0;

      for (i; i < word.length; i++){

      points += letters.get(word.charAt(i));

      }

      if (score == "D"){
      points *= 2;
      }
      else if (score == "T"){
      points *= 3;
      }

      System.out.println(points);

Related Searches:

References

Comments

Related Ads

Featured