javaarraysjava.util.scannerscrabble

Scrabble array in java


So for a class, I need to make a program that scores a word based off of scrabble values for a letter. So aa should be 2 since 1 a is worth 1 point. But for some reason, my program only shows aa as 1 point.

import java.util.Scanner;

public class Scrabble {   
       public static void main(String[] args) {
            String[] alphabet = {"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"};

            int[] values = {1, 3, 3, 2, 1, 4,  
               2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10,
               1, 1, 1, 1, 4, 4, 8, 4, 10};

            Scanner kboard = new Scanner(System.in);
            System.out.println("Input your word.");

            String choice = kboard.nextLine();

            int score = 0;
            for(int i = 0; i < choice.length(); i++) {
                for(int n = 0; n < 26; n++)   {
                    if(choice.substring(i).equals(alphabet[n]))
                    {
                       score += values[n];
                    }
                }
             }

             System.out.println("The score for your word is " + score);
       }

}

Solution

  • The problem is that someStr.substring(i) doesn't return only a single letter. For example, the output of System.out.println("aaa".substring(1)); is "aa", not a.

    Here's a modified version:

    char[] alphabet = {'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'}; 
    int[] values = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
    Scanner kboard = new Scanner(System.in); System.out.println("Input your word.");
    String choice = kboard.nextLine();
    int score = 0;
    for(int i = 0; i < choice.length(); i++) {
      for(int n = 0; n < 26; n++) {
        // Use charAt here instead of substring
        if(choice.charAt(i) == alphabet[n])
        {
          score += values[n];
        }
      }
    }
    System.out.println("The score for your word is " + score);
    

    }

    Even better, you could just use a Hash Table for the alphabet and avoid the inner loop.