- (10%) The following program fails to compile. Why does it fail to compile?
public class BrokenA { public static final double RATE = 0.5; public static void main(String[] args) { double x = 0; x = 10 * RATE; RATE = 20; } }
Answer: Because we are trying to re-set the value ofRATE
which is afinal
variable.
- (40%) What does the program below print when it runs?
import java.util.Scanner; public class Mystery { public static void main(String[] args) { String sentence = "A rebel without a clue"; for (int i = 0; i < sentence.length(); i++){ char c = sentence.charAt(i); int r = 0; for (int j = 0; j < sentence.length(); j++){ if (sentence.charAt(j) == c) r++; } System.out.println(c + ":" + r); } } }
Answer:
A:1 :4 r:1 e:3 b:1 e:3 l:2 :4 w:1 i:1 t:2 h:1 o:1 u:2 t:2 :4 a:1 :4 c:1 l:2 u:2 e:3
- (50%) Write a program that:
- Asks the user to enter any number of words. If the user enters the word done then the program ends. You can assume the user will always enter a word (he will not type in spaces, numbers, etc.)
- After the user enters each word you will print out a score such that:
- If a word has 9 or fewer letters the score is 2 times the number of letters.
- If a word has 10 or more letters the score is 10 plus 2 times the number of letters.
- If a word starts with the letter 'z' then it gets a score of 500, regardless of how many letters it has.
- After the user enters done, you print out the longest word.
Enter word:hello Score=10 Enter word:howareyouthere Score=38 Enter word:a Score=2 Enter word:z Score=500 Enter word:zoologically Score=500 Enter word:done The longest word was howareyouthere
Answer:
import java.util.Scanner; public class WordChecker { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String longest = ""; while (true){ System.out.print("Enter word:"); String word = keyboard.next(); if (word.equalsIgnoreCase("done")) break; System.out.print("Score="); if (word.substring(0,1).equalsIgnoreCase("z")) System.out.println(500); else if (word.length() > 10) System.out.println(10 + 2*word.length()); else System.out.println(2*word.length()); if (word.length() > longest.length()) longest = word; } System.out.println("The longest word was " + longest); } }
Tuesday, September 29, 2009
Test 1 Solutions and Grades
Below is our first test, along with the answers.
Subscribe to:
Post Comments (Atom)
2 comments:
Is this test going to be curved?
You are guaranteed the grade given by the standard curve (A is 90+ etc.)
However, the final grade in the class will likely be curved lower than that.
Post a Comment