kennycodes
kennycodes

Reputation: 536

Scrabble code in java

I have to write a scrabble code in java without the use of if/switch statements. this is what i have so far

public class Scrabble {


public static void main(String[] args) {
}

    public static int computeScore(String word) {

String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int[] values = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,3,3,10,1,1,1,1,4,4,8,4,10};
    int sum = 0;
    for(int i = 0; i <word.length();i++) {
        ????

    }
return sum;

}

}

I need some help, I had the idea of finding the character inside the string and finding its value but not sure how to write it out. Any help will be great! Thanks!

Upvotes: 0

Views: 15239

Answers (1)

James C. Taylor IV
James C. Taylor IV

Reputation: 609

Inside you for loop you would need to do the following:

sum += values[aplphabet.indexOf(word.charAt(i))];

So your loop should so something like:

for(int i = 0; i <word.length();i++) {
    sum += values[aplphabet.indexOf(word.charAt(i))];
}

This will of course not handle any modifier tiles on the scrabble board.

Alternatively you can use a HashMap<char, int> to store your letters, so that accessing them is a bit easier:

public class Scrabble {

    HashMap<char, int> alphabet;

    public static void main(String[] args) {

        //initialize the alphabet and store all the values
        alphabet = new HashMap<char, int>();
        alpahbet.put('A', 1);
        alpahbet.put('B', 3);
        alpahbet.put('C', 3);
        //...
        alpahbet.put('Z', 10);
    }

    public static int computeScore(String word) {
        int sum = 0;
        for(int i = 0; i <word.length();i++) {
            //look up the current char in the alphabet and add it's value to sum
            sum += alphabet.get(word.charAt(i));
        }
        return sum;

    }

}

Upvotes: 1

Related Questions