Java Reference
In-Depth Information
7. The code won't ever print "Mine, too!" because it mistakenly uses the ==
operator to compare two string objects. It should use the equals method to com-
pare them:
if (name.equals("blue")) {...
8. int sum = 1000;
Scanner console = new Scanner(System.in);
System.out.print(
"Is your money multiplied 1 or 2 times? ");
int times = console.nextInt();
System.out.print("And how much are you contributing? ");
int donation = console.nextInt();
sum += times * donation;
total += donation;
if (times == 1) {
count1++;
}
else if (times == 2) {
count2++;
}
If the user could type any number, the code might need additional if statements to
increment the proper count variable. If the user could type anything, even a non-
integer, the code might need to use the hasNextInt method of the Scanner (seen
in Chapter 5) to ensure that it has received valid input before it proceeds.
9. // Prompts for two people's money and reports
// how many $20 bills the person would need.
import java.util.*;
public class Bills {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int numBills1 = getBills(console, "John");
int numBills2 = getBills(console, "Jane");
System.out.println("John needs " + numBills1 +
" bills");
System.out.println("Jane needs " + numBills2 +
" bills");
}
public static int getBills(Scanner console,
String name) {
System.out.print("How much will " + name +
" be spending? ");
Search WWH ::




Custom Search