Java Reference
In-Depth Information
print an error message. Make your program case-insensitive so that the user can type an uppercase or lowercase letter.
Here are some example executions:
What color do you want? B
You have chosen Blue.
What color do you want? g
You have chosen Green.
What color do you want? Bork
Unknown color: Bork
11.
Write a piece of code that reads a shorthand text description of a playing card and prints the longhand equivalent.
The shorthand description is the card's rank (
2
through
10
,
J
,
Q
,
K
, or
A
) followed by its suit (
C
,
D
,
H
, or
S
). You
should expand the shorthand into the form “<Rank> of <Suit>”. You may assume that the user types valid input.
Here are two sample executions:
Enter a card: 9 S
Nine of Spades
Enter a card: K C
King of Clubs
Section 4.2: Cumulative Algorithms
12.
What is wrong with the following code, which attempts to add all numbers from 1 to a given maximum? Describe
how to fix the code.
public static int sumTo(int n) {
for (int i = 1; i <= n; i++) {
int sum = 0;
sum += i;
}
return sum;
}
13.
What is wrong with the following code, which attempts to return the number of factors of a given integer
n
?
Describe how to fix the code.
public static int countFactors(int n) {
for (int i = 1; i <= n; i++) {
if (n % i == 0) { // factor
return i;
}
}
}
Search WWH ::
Custom Search