25a-section-3-solutions

25a-section-3-solutions - private int...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Handout #25A CS 106A July 16, 2009 Solution to Section #3 1. Scrabble scoring /* * File: ScrabbleScore.java * ------------------------ * This program reads in words and calculates their score in * Scrabble. Only uppercase letters count, so that it is possible * to use lowercase letters to indicate blanks, so that the input * "QUIZzICAL" shows that the second Z is actually a blank. */ import acm.program.*; public class ScrabbleScore extends ConsoleProgram { /** Runs the program */ public void run() { println("Program to compute Scrabble scores"); while (true) { String word = readLine("Enter a word: "); if (word.length() == 0) break; println(word + " scores " + scoreScrabbleWord(word)); } } /** Computes the score for a Scrabble word */ private int scoreScrabbleWord(String word) { int score = 0; for (int i = 0; i < word.length(); i++) { score += scoreScrabbleLetter(word.charAt(i)); } return score; } /** Computes the score for a Scrabble letter */
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: private int scoreScrabbleLetter(char ch) { if (!Character.isUpperCase(ch)) return 0; switch (ch) { case 'Q': case 'Z': return 10; case 'J': case 'X': return 8; case 'K': return 5; case 'F': case 'H': case 'V': case 'W': case 'Y': return 4; case 'B': case 'C': case 'M': case 'P': return 3; case 'D': case 'G': return 2; default: return 1; } } } – 2 – 2. Adding commas to numeric strings private String addCommasToNumericString(String digits) { String result = ""; int len = digits.length(); int nDigits = 0; for (int i = len - 1; i >= 0; i--) { result = digits.charAt(i) + result; nDigits++; if (nDigits % 3 == 0 && i > 0) { result = "," + result; } } return result; } 3. Deleting characters from a string private String removeAllOccurrences(String str, char ch) { String result = ""; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != ch) result += str.charAt(i); } return result; }...
View Full Document

This note was uploaded on 10/14/2010 for the course CS 106A taught by Professor Sahami,m during the Fall '08 term at Stanford.

Page1 / 2

25a-section-3-solutions - private int...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online