Java Reference
In-Depth Information
} else if (rank.equals("J")) {
rank = "Jack";
} else if (rank.equals("Q")) {
rank = "Queen";
} else if (rank.equals("K")) {
rank = "King";
} else { // rank.equals("A")
rank = "Ace";
}
if (suit.equals("C")) {
suit = "Clubs";
} else if (suit.equals("D")) {
suit = "Diamonds";
} else if (suit.equals("H")) {
suit = "Hearts";
} else { // suit.equals("S")
suit = "Spades";
}
System.out.println(rank + " of " + suit);
12. The sum variable needs to be declared outside the for loop. The following code
fixes the problem:
public static int sumTo(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
13. The method will not compile. It should count the factors using a cumulative sum;
it should not return inside the loop when it finds each factor. Instead, it should
declare a counter outside the loop that is incremented as each factor is seen. The
following code fixes the problem:
public static int countFactors(int n) {
int count = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
count++;
}
}
return count;
}
Search WWH ::




Custom Search