Download presentation
Presentation is loading. Please wait.
Published byMyra Stafford Modified over 9 years ago
1
Starting Out with Java: From Control Structures through Objects
5th edition By Tony Gaddis Source Code: Chapter 6
2
Code Listing 6-1 (ObjectDemo.java)
1 import java.util.Scanner; // Needed for the Scanner class 2 import java.util.Random; // Needed for the Random class 3 import java.io.*; // Needed for file I/O classes 4 5 /* 6 This program writes random numbers to a file. 7 */ 8 9 public class ObjectDemo 10 { 11 public static void main(String[] args) throws IOException 12 { 13 int maxNumbers; // Max number of random numbers 14 int number; // To hold a random number 15 16 // Create a Scanner object for keyboard input. 17 Scanner keyboard = new Scanner(System.in); 18 19 // Create a Random object to generate random numbers. 20 Random rand = new Random(); 21 22 23 PrintWriter outputFile = new PrintWriter("numbers.txt"); (Continued)
3
Program Output with Example Input Shown in Bold
24 25 // Get the number of random numbers to write. 26 System.out.print("How many random numbers should I write? "); 27 maxNumbers = keyboard.nextInt(); 28 29 // Write the random numbers to the file. 30 for (int count = 0; count < maxNumbers; count++) 31 { 32 33 number = rand.nextInt(); 34 // Write the random integer to the file. 36 outputFile.println(number); 37 } 38 39 // Close the file. 40 outputFile.close(); 41 System.out.println("Done"); 42 } 43 } Program Output with Example Input Shown in Bold How many random numbers should I write? 10 [ Enter] Done
4
Code Listing 6-2 (Rectangle.java)
1 /** 2 Rectangle class, phase 1 3 Under construction! 4 */ 5 6 public class Rectangle 7 { 8 private double length; 9 private double width; 10 11 /** 12 The setLength method stores a value in the 13 length field. 14 @param len The value to store in length. 15 */ 16 17 public void setLength( double len ) 18 { 19 length = len; 20 } 21 }
5
Code Listing 6-3 (LengthDemo.java)
1 /** 2 This program demonstrates the Rectangle class's 3 setLength method. 4 */ 5 6 public class LengthDemo 7 { 8 public static void main(String[] args) 9 { 10 // Create a Rectangle object. 12 Rectangle box = new Rectangle(); // Constructor method? 13 14 15 System.out.println("Sending the value 10.0 " + "to the setLength method."); 17 // Call the box object's setLength method. 19 box.setLength(10.0); (Continued)
6
20 // Indicate we are done. 22 System.out.println("Done."); 23 } // end main 24 } // end class Program Output Sending the value 10.0 to the setLength method. Done.
7
Code Listing 6-4 (Rectangle.java)
1 /** 2 Rectangle class, phase 2 3 Under construction! 4 */ 5 6 public class Rectangle 7 { 8 private double length; 9 private double width; 10 11 /** 12 The setLength method stores a value in the 13 length field. 14 @param len The value to store in length. 15 */ 16 17 public void setLength( double len ) 18 { 19 length = len; 20 } 21 (Continued)
8
22 /** 23 The setWidth method stores a value in the 24 width field. @param w The value to store in width. 26 */ 27 28 public void setWidth(double w) { width = w; 31 } 32 }
9
Code Listing 6-5 (Rectangle.java)
1 /** 2 Rectangle class, phase 3 3 Under construction ! 4 */ 5 6 public class Rectangle 7 { 8 private double length; 9 private double width; 10 11 /** 12 The setLength method stores a value in the 13 length field. 14 @param len The value to store in length. 15 */ 16 17 public void setLength(double len) 18 { 19 length = len; 20 } 21 (Continued)
10
22 /** 23 The setWidth method stores a value in the 24 width field. 25 @param w The value to store in width. 26 */ 27 28 public void setWidth(double w) 29 { 30 width = w; 31 } 32 33 /** 34 The getLength method returns a Rectangle 35 object's length. 36 @return The value in the length field. 37 */ 38 39 public double getLength() 40 { 41 return length; 42 } 43 (Continued)
11
44 /** 45 The getWidth method returns a Rectangle 46 object's width. 47 @return The value in the width field. 48 */ 49 50 public double getWidth() 51 { 52 return width; 53 } 54 }
12
Code Listing 6-6 (LengthWidthDemo.java)
1 /** 2 This program demonstrates the Rectangle class's 3 setLength, setWidth, getLength, and getWidth methods. 4 */ 5 6 public class LengthWidthDemo 7 { 8 public static void main(String[] args) 9 { 10 // Create a Rectangle object. 11 Rectangle box = new Rectangle(); 12 13 // Call the object's setLength method, passing 10.0 14 // as an argument. 15 box.setLength(10.0); 16 17 // Call the object's setWidth method, passing 20.0 18 // as an argument. 19 box.setWidth(20.0); 20 (Continued)
13
Program Output The box's length is 10.0 The box's width is 20.0
// Display the object's length and width. 22 System.out.println("The box's length is " + box.getLength()); 24 System.out.println("The box's width is " + box.getWidth()); 26 } 27 } Program Output The box's length is 10.0 The box's width is 20.0
14
Code Listing 6-7 (Rectangle.java)
1 /** 2 Rectangle class, phase 4 3 Under construction! 4 */ 5 6 public class Rectangle 7 { 8 private double length; 9 private double width; 10 11 /** 12 The setLength method stores a value in the 13 length field. 14 @param len The value to store in length. 15 */ 16 17 public void setLength( double len ) 18 { 19 length = len; 20 } 21 (Continued)
15
22 /** 23 The setWidth method stores a value in the 24 width field. 25 @param w The value to store in width. 26 */ 27 28 public void setWidth( double w ) 29 { 30 width = w; 31 } 32 33 /** 34 The getLength method returns a Rectangle 35 object's length. 36 @return The value in the length field. 37 */ 38 39 public double getLength() 40 { 41 return length; 42 } 43 (Continued)
16
44 /** 45 The getWidth method returns a Rectangle 46 object's width. 47 @return The value in the width field. 48 */ 49 50 public double getWidth() 51 { 52 return width; 53 } 54 55 /** 56 The getArea method returns a Rectangle 57 object's area. 58 @return The product of length times width. 59 */ 60 61 public double getArea() // What is Stale data? 62 { 63 return length * width; 64 } 65 }
17
Code Listing 6-8 (RectangleDemo.java)
1 /** 2 This program demonstrates the Rectangle class's 3 setLength, setWidth, getLength, getWidth, and 4 getArea methods. 5 */ 6 7 public class RectangleDemo 8 { 9 public static void main(String[] args) 10 { // Create a Rectangle object. 12 Rectangle box = new Rectangle(); 13 15 box.setLength(10.0); 16 box.setWidth(20.0); 17 // Display the length. 19 System.out.println("The box's length is " + box.getLength()); (Continued)
18
Program Output The box's length is 10.0 The box's width is 20.0
21 // Display the width. 23 System.out.println("The box's width is " + box.getWidth()); 25 // Display the area. 27 System.out.println("The box's area is " + box.getArea()); 29 } 30 } Program Output The box's length is 10.0 The box's width is 20.0 The box's area is 200.0
19
Code Listing 6-9 (RoomAreas.java)
1 import javax.swing.JOptionPane; 2 3 /** 4 This program creates three instances of the 5 Rectangle class. 6 */ 7 8 public class RoomAreas 9 { 10 public static void main(String[] args) 11 { 12 double number; // To hold a number 13 double totalArea; // The total area 14 String input; // To hold user input 15 // Create three Rectangle objects. 17 Rectangle kitchen = new Rectangle(); 18 Rectangle bedroom = new Rectangle(); 19 Rectangle den = new Rectangle(); 20 (Continued)
20
22 input = JOptionPane.showInputDialog("What is the " +
"kitchen's length?"); 24 number = Double.parseDouble(input); kitchen.setLength(number); 26 input = JOptionPane.showInputDialog("What is the " + "kitchen's width?"); 28 number = Double.parseDouble(input); kitchen.setWidth(number); 30 // Get and store the dimensions of the bedroom. 32 input = JOptionPane.showInputDialog("What is the " + "bedroom's length?"); 34 number = Double.parseDouble(input); bedroom.setLength(number); 36 input = JOptionPane.showInputDialog("What is the " + "bedroom's width?"); 38 number = Double.parseDouble(input); 39 bedroom.setWidth(number); 40 (Continued)
21
42 input = JOptionPane.showInputDialog("What is the " +
"den's length?"); 44 number = Double.parseDouble(input); 45 den.setLength(number); 46 input = JOptionPane.showInputDialog("What is the " + "den's width?"); 48 number = Double.parseDouble(input); 49 den.setWidth(number); 52 totalArea = kitchen.getArea() + bedroom.getArea() den.getArea(); 54 56 JOptionPane.showMessageDialog(null, " + "The total area” + "of the rooms is " + totalArea); 58 59 System.exit(0); 60 } 61 }
22
17 { 18 length = len; 19 width = w; }
Code Listing 6-10 (Rectangle.java) 1 /** 2 Rectangle class, phase 5 3 */ 4 5 public class Rectangle 6 { 7 private double length; 8 private double width; 9 10 /** 11 Constructor 12 @param len The length of the rectangle. 13 @param w The width of the rectangle. 14 */ 15 16 public Rectangle( double len, double w ) 17 { 18 length = len; 19 width = w; } . . . The remainder of the class has not changed, and is not shown.
23
Code Listing 6-11 (ConstructorDemo.java)
1 /** 2 This program demonstrates the Rectangle class's 3 constructor. 4 */ 5 6 public class ConstructorDemo 7 { 8 public static void main(String[] args) 9 { 10 // Create a Rectangle object, passing 5.0 and // 15.0 as arguments to the constructor. 12 Rectangle box = new Rectangle( 5.0, 15.0 ); 13 14 // Display the length. 15 System.out.println("The box's length is " + box.getLength()); 17 18 // Display the width. 19 System.out.println("The box's width is " + box.getWidth()); 21 (Continued)
24
Program Output The box's length is 5.0 The box's width is 15.0
22 // Display the area. 23 System.out.println("The box's area is " + box.getArea()); 25 } 26 } Program Output The box's length is 5.0 The box's width is 15.0 The box's area is 75.0
25
Code Listing 6-12 (CellPhone.java)
1 /** 2 The CellPhone class holds data about a cell phone. 3 */ 4 5 public class CellPhone 6 { 7 // Fields 8 private String manufact; // Manufacturer 9 private String model; // Model 10 private double retailPrice; // Retail price 11 12 /** 13 Constructor 14 @param man The phone's manufacturer. 15 @param mod The phone's model number. 16 @param price The phone's retail price. 17 */ 18 19 public CellPhone( String man, String mod, double price ) 20 { 21 manufact = man; 22 model = mod; 23 retailPrice = price; (Continued)
26
27 The setManufact method sets the phone's 28 manufacturer name.
24 } 25 26 /** 27 The setManufact method sets the phone's 28 manufacturer name. 29 @param man The phone's manufacturer. 30 */ 31 32 public void setManufact( String man ) 33 { 34 manufact = man; 35 } 36 37 /** 38 The setMod method sets the phone's 39 model number. 40 @param mod The phone's model number. 41 */ 42 43 public void setMod( String mod ) 44 { 45 model = mod; 46 } (Continued)
27
49 The setRetailPrice method sets the phone's 50 retail price.
47 48 /** 49 The setRetailPrice method sets the phone's 50 retail price. 51 @param price The phone's retail price. 52 */ 53 54 public void setRetailPrice( double price ) 55 { 56 retailPrice = price; 57 } 58 59 /** 60 getManufact method 61 @return The name of the phone's manufacturer. 62 */ 63 64 public String getManufact() 65 { 66 return manufact; 67 } 68 (Continued)
28
71 @return The phone's model number. 72 */ 73
69 /** 70 getModel method 71 @return The phone's model number. 72 */ 73 74 public String getModel() 75 { 76 return model; 77 } 78 79 /** 80 getretailPrice method 81 @return The phone's retail price. 82 */ 83 84 public double getRetailPrice() 85 { 86 return retailPrice; 87 } 88 }
29
Code Listing 6-13 (CellPhoneTest.java)
1 import java.util.Scanner; 2 3 /** 4 This program runs a simple test 5 of the CellPhone class. 6 */ 7 8 public class CellPhoneTest 9 { 10 public static void main(String[] args) { 12 String testMan; // To hold a manufacturer 13 String testMod; // To hold a model number 14 double testPrice; // To hold a price 15 16 // Create a Scanner object for keyboard input. 17 Scanner keyboard = new Scanner(System.in); 18 19 // Get the manufacturer name. 20 System.out.print("Enter the manufacturer: "); 21 testMan = keyboard.nextLine(); 22 (Continued)
30
23 // Get the model number. 24 System.out.print("Enter the model number: "); 25 testMod = keyboard.nextLine(); 26 27 // Get the retail price. 28 System.out.print("Enter the retail price: "); testPrice = keyboard.nextDouble(); // Create an instance of the CellPhone class, 31 32 34 CellPhone phone = new CellPhone( testMan, testMod, testPrice ); 35 36 // Get the data from the phone and display it. 37 System.out.println(); 38 System.out.println("Here is the data that you provided:"); 39 System.out.println("Manufacturer: " + phone.getManufact()); 40 System.out.println("Model number: " + phone.getModel()); 41 System.out.println("Retail price: " + phone.getRetailPrice()); 42 } 43 } (Continued)
31
Program Output with Example Input Shown in Bold
Enter the manufacturer: Acme Electronics [ Enter ] Enter the model number: M1000 [ Enter ] Enter the retail price: [ Enter ] Here is the data that you provided: Manufacturer: Acme Electronics Model number: M1000 Retail price: $199.99
32
18 public Die( int numSides ) 19 { 20 sides = numSides;
Code Listing 6-14 (Die.java) 1 import java.util.Random; 2 3 /** 4 The Die class simulates a die of varying sizes. 5 */ 6 7 public class Die 8 { 9 private int sides; // Number of sides 10 private int value; // The die's value 11 12 /** 13 The constructor performs an initial 14 roll of the die. 15 @param numSides The number of sides for this die. 16 */ 17 18 public Die( int numSides ) 19 { 20 sides = numSides; 21 roll(); // What are we calling? 22 } 23 (Continued)
33
25 The roll method simulates the rolling of 26 the die. 27 */ 28
24 /** 25 The roll method simulates the rolling of 26 the die. 27 */ 28 29 public void roll() 30 { 31 // Create a Random object. 32 Random rand = new Random(); 33 34 // Get a random value for the die. 35 value = rand.nextInt(sides) + 1; // What is value? 36 } 37 38 /** 39 getSides method 40 @return The number of sides for this die. 41 */ 42 43 public int getSides() 44 { 45 return sides; // What is sides? 46 } (Continued)
34
47 48 /** 49 getValue method 50 @return The value of the die. 51 */ 52 53 public int getValue() 54 { 55 return value; 56 } 57 } End Class
35
Code Listing 6-15 (DiceDemo.java)
1 /** 2 This program simulates the rolling of dice. 3 */ 4 5 public class DiceDemo 6 { 7 public static void main(String[] args) 8 { 9 final int DIE1_SIDES = 6; // Number of sides for die #1 10 final int DIE2_SIDES = 12; // Number of sides for die #2 11 final int MAX_ROLLS = 5; // Number of times to roll 13 14 Die die1 = new Die(DIE1_SIDES); 15 Die die2 = new Die(DIE2_SIDES); 16 17 // Display the initial state of the dice. 18 System.out.println("This simulates the rolling of a " + DIE1_SIDES + " sided die and a " + DIE2_SIDES + " sided die."); 21 22 System.out.println("Initial value of the dice:"); // ? 23 System.out.println( die1.getValue() + " " + die2.getValue() ); (Continued)
36
This simulates the rolling of a 6 sided die and a 12 sided die.
// Roll the dice five times. 26 System.out.println("Rolling the dice " + MAX_ROLLS + " times."); 27 28 for (int i = 0; i < MAX_ROLLS; i++) 29 { 30 // Roll the dice. 31 die1.roll(); 32 die2.roll(); 33 34 // Display the values of the dice. 35 System.out.println( die1.getValue() + " " + die2.getValue() ); 36 } 37 } // End main 38 } // End Class Program Output This simulates the rolling of a 6 sided die and a 12 sided die. Initial value of the dice: 2 7 Rolling the dice 5 times. 3 5 5 2 2 1 4 1 5 9
37
21 rollDie(twentyDie); // Passing a Reference as an Argument
Code Listing 6-16 (DieArgument.java) 1 /** 2 This program rolls a 6-sided die and 3 a 20-sided die. Client of Die. 4 */ 5 6 public class DieArgument 7 { 8 public static void main(String[] args) 9 { 10 final int SIX_SIDES = 6; 11 final int TWENTY_SIDES = 20; 12 13 14 Die sixDie = new Die(SIX_SIDES); 15 16 17 Die twentyDie = new Die(TWENTY_SIDES); 18 // Roll the dice. 20 rollDie(sixDie); // What type of method? 21 rollDie(twentyDie); // Passing a Reference as an Argument 22 } (Continued)
38
Program Output Rolling a 6 sided die. The die's value: 3
23 24 /** 25 This method simulates a die roll, displaying 26 the die's number of sides and value. 27 @param d The Die object to roll. 28 */ 29 30 public static void rollDie(Die d) // Receiving the Reference Argument 31 { 32 // Display the number of sides. 33 System.out.println("Rolling a " + d.getSides() + " sided die."); 35 36 // Roll the die. 37 d.roll(); 38 39 // Display the die's value. 40 System.out.println("The die's value: " + d.getValue()); 41 } 42 } Program Output Rolling a 6 sided die. The die's value: 3 Rolling a 20 sided die. The die's value: 19
39
Code Listing 6-17 (Dealer.java)
1 /** 2 Dealer class for the game of Cho-Han( Uses Die class ) 3 */ 4 5 public class Dealer 6 { 7 private int die1Value; // The value of die #1 8 private int die2Value; // The value of die #2 9 10 /** 11 Constructor 12 */ 13 14 public Dealer() 15 { 16 die1Value = 0; 17 die2Value = 0; 18 } 19 20 /** 21 The rollDice method rolls the dice and saves 22 their values. 23 */ (Continued)
40
24 25 public void rollDice() 26 { 27 final int SIDES = 6; // Number of sides for the dice 28 29 // Create the two dice. (This also rolls them.) 30 Die die1 = new Die(SIDES); 31 Die die2 = new Die(SIDES); 32 33 34 die1Value = die1.getValue(); // Where is memory for die1Value 35 die2Value = die2.getValue(); // and die2Value allocated? 36 } 37 38 /** 39 The getChoOrHan method returns the result of 40 the dice roll, Cho or Han. 41 @return Either "Cho (even)" or "Han (odd)" 42 */ 43 44 public String getChoOrHan() 45 { 46 String result; // To hold the result (Continued)
41
48 // Get the sum of the dice. 49 int sum = die1Value + die2Value; 50
47 48 // Get the sum of the dice. 49 int sum = die1Value + die2Value; 50 51 // Determine even or odd. 52 if (sum % 2 == 0) 53 result = "Cho (even)"; 54 else 55 result = "Han (odd)"; 56 57 // Return the result. 58 return result; 59 } 60 61 /** 62 The getDie1Value method returns the value of 63 die #1. 64 @return The die1Value field 65 */ 66 (Continued)
42
67 public int getDie1Value()
68 { 69 return die1Value; 70 } 71 72 /** 73 The getDie2Value method returns the value of 74 die #2. 75 @return The die2Value field 76 */ 77 78 public int getDie2Value() 79 { return die2Value; } 82 }
43
Code Listing 6-18 (Player.java)
1 import java.util.Random; 2 3 /** 4 Player class for the game of Cho-Han 5 */ 6 7 public class Player 8 { 9 private String name; // The player's name 10 private String guess; // The player's guess 11 private int points; // The player's points 12 13 /** 14 Constructor 15 @param playerName The player's name. 16 */ 17 18 public Player(String playerName) 19 { 20 name = playerName; 21 guess = ""; 22 points = 0; 23 } (Continued)
44
40 if (guessNumber == 0) 41 guess = "Cho (even)"; 42 else
24 25 /** 26 The makeGuess method causes the player to guess 27 either "Cho (even)" or "Han (odd)". 28 */ 29 30 public void makeGuess() 31 { 33 Random rand = new Random(); 34 int guessNumber = rand.nextInt(2); 37 38 // Convert the random number to a guess of // either "Cho (even)" or "Han (odd)". 40 if (guessNumber == 0) 41 guess = "Cho (even)"; 42 else 43 guess = "Han (odd)"; 44 } 45 (Continued)
45
47 The addPoints method adds a specified number of
46 /** 47 The addPoints method adds a specified number of 48 points to the player's current balance. 49 @newPoints The points to add. 50 */ 51 52 public void addPoints(int newPoints) 53 { 54 points += newPoints; 55 } 56 57 /** 58 The getName method returns the player's name. 59 @return The value of the name field. 60 */ 61 62 public String getName() 63 { 64 return name; 65 } 66 (Continued)
46
67 /** 68 The getGuess method returns the player's guess. 69 @return The value of the guess field. 70 */ 71 72 public String getGuess() 73 { 74 return guess; 75 } 76 77 /** 78 The getPoints method returns the player's points 79 @return The value of the points field. 80 */ 81 82 public int getPoints() 83 { 84 return points; 85 } 86 }
47
Code Listing 6-19 (ChoHan.java)
1 import java.util.Scanner; 2 3 public class ChoHan 4 { 5 public static void main(String[] args) 6 { 7 final int MAX_ROUNDS = 5; // Number of rounds 8 String player1Name; // First player's name 9 String player2Name; // Second player's name 10 11 12 Scanner keyboard = new Scanner(System.in); 13 15 System.out.print("Enter the first player's name: "); player1Name = keyboard.nextLine(); 17 System.out.print("Enter the second player's name: "); 18 player2Name = keyboard.nextLine(); 19 20 // Create the dealer. 21 Dealer dealer = new Dealer(); 22 (Continued)
48
// Display the grand winner.
23 // Create the two players. 24 Player player1 = new Player(player1Name); 25 Player player2 = new Player(player2Name); 26 27 // Play the rounds. 28 for (int round = 0; round < MAX_ROUNDS; round++) 29 { 30 System.out.println(" "); 31 System.out.printf("Now playing round %d.\n", round + 1); 32 33 // Roll the dice. 34 dealer.rollDice(); 35 36 // The players make their guesses. 37 player1.makeGuess(); 38 player2.makeGuess(); 39 40 // Determine the winner of this round. 41 roundResults( dealer, player1, player2 ); 42 } 43 // Display the grand winner. 45 displayGrandWinner( player1, player2 ); (Continued)
49
46 } // End Main 47 48 /** 49 The roundResults method determines the results of 50 the current round. 51 @param dealer The Dealer object 52 @param player1 Player #1 object 53 @param player2 Player #2 object 54 */ 55 56 public static void roundResults( Dealer dealer, Player player1, Player player2 ) 58 { 59 // Show the dice values. 60 System.out.printf("The dealer rolled %d and %d.\n", dealer.getDie1Value(), dealer.getDie2Value()); 62 System.out.printf("Result: %s\n", dealer.getChoOrHan() ); 63 64 // Check each player's guess and award points. 65 checkGuess( player1, dealer ); 66 checkGuess( player2, dealer ); 67 } (Continued)
50
68 69 /** 70 The checkGuess method checks a player's guess against 71 the dealer's result. 72 @param player The Player object to check. 73 @param dealer The Dealer object. 74 */ 75 76 public static void checkGuess( Player player, Dealer dealer ) 77 { 78 final int POINTS_TO_ADD = 1; // Points to award winner 79 String guess = player.getGuess(); // Player's guess 80 String choHanResult = dealer.getChoOrHan(); // Cho or Han 81 82 // Display the player's guess. 83 System.out.printf("The player %s guessed %s.\n", 84 player.getName(), player.getGuess()); 85 // Award points if the player guessed correctly. 87 if (guess.equalsIgnoreCase( choHanResult) ) (Continued)
51
88 { 89 player.addPoints(POINTS_TO_ADD); 90 System.out.printf("Awarding %d point(s) to %s.\n", POINTS_TO_ADD, player.getName() ); 92 } 93 } // End checkGuess 94 95 /** 96 The displayGrandWinner method displays the game's grand winner. 97 @param player1 Player #1 98 @param player2 Player #2 99 */ 100 101 public static void displayGrandWinner( Player player1, Player player2 ) 102 { 103 System.out.println(" "); 104 System.out.println("Game over. Here are the results:"); 105 System.out.printf("%s: %d points.\n", player1.getName(), player1.getPoints()); 107 System.out.printf("%s: %d points.\n", player2.getName(), player2.getPoints()); 109 (Continued)
52
Enter the first player's name: Chelsea [ Enter ]
110 if ( player1.getPoints() > player2.getPoints() ) System.out.println( player1.getName() + " is the grand winner!"); 112 else if ( player2.getPoints() > player1.getPoints() ) System.out.println( player2.getName() + " is the grand winner!"); 114 else System.out.println("Both players are tied!"); 116 } 117 } Program Output Enter the first player's name: Chelsea [ Enter ] Enter the second player's name: Chris [ Enter ] Now playing round 1. The dealer rolled 3 and 6. Result: Han (odd) The player Chelsea guessed Han (odd). Awarding 1 point(s) to Chelsea. The player Chris guessed Han (odd). Awarding 1 point(s) to Chris. (Continued)
53
----------------------------
Now playing round 2. The dealer rolled 4 and 5. Result: Han (odd) The player Chelsea guessed Cho (even). The player Chris guessed Cho (even). Now playing round 3. The dealer rolled 5 and 6. The player Chris guessed Han (odd). Awarding 1 point(s) to Chris. Now playing round 4. The dealer rolled 1 and 6. (Continued)
54
Chris is the grand winner!
Now playing round 5. The dealer rolled 6 and 6. Result: Cho (even) The player Chelsea guessed Han (odd). The player Chris guessed Cho (even). Awarding 1 point(s) to Chris. Game over. Here are the results: Chelsea: 1 points. Chris: points. Chris is the grand winner!
55
Code Listing 6-20 (BankAccount.java)
1 /** 2 The BankAccount class simulates a bank account. 3 */ 4 5 public class BankAccount 6 { 7 private double balance; // Account balance Data field( Instance Variable ) 8 9 /** 10 This constructor - 1 sets the starting balance 11 at 0.0. 12 */ 13 14 public BankAccount() 15 { 16 balance = 0.0; 17 } 18 19 /** 20 This constructor - 2 sets the starting balance 21 to the value passed as an argument. 22 @param startBalance The starting balance. 23 */ (Continued)
56
24 25 public BankAccount( double startBalance ) 26 { 27 balance = startBalance; 28 } 29 30 /** 31 This constructor – 3 sets the starting balance 32 to the value in the String argument. 33 @param str The starting balance, as a String. 34 */ 35 36 public BankAccount( String str ) 37 { 38 balance = Double.parseDouble(str); 39 } 40 41 /** 42 The deposit method – 1 makes a deposit into 43 the account. 44 @param amount The amount to add to the 45 balance field. 46 */ (Continued)
57
47 48 public void deposit( double amount ) 49 { 50 balance += amount; 51 } 52 53 /** 54 The deposit method – 2 makes a deposit into 55 the account. 56 @param str The amount to add to the 57 balance field, as a String. 58 */ 59 60 public void deposit(String str) 61 { 62 balance += Double.parseDouble(str); 63 } 64 65 /** 66 The withdraw method - 1 withdraws an amount 67 from the account. 68 @param amount The amount to subtract from (Continued)
58
69 the balance field. 70 */ 71 72 public void withdraw( double amount ) 73 { 74 balance -= amount; 75 } 76 77 /** 78 The withdraw method – 2 withdraws an amount 79 from the account. 80 @param str The amount to subtract from 81 the balance field, as a String. 82 */ 83 84 public void withdraw( String str ) 85 { 86 balance -= Double.parseDouble(str); 87 } 88 89 /** 90 The setBalance method - 1 sets the account balance. (Continued)
59
91 @param b The value to store in the balance field.
92 */ 93 94 public void setBalance(double b) 95 { 96 balance = b; 97 } 98 99 /** 100 The setBalance method – 2 sets the account balance. 101 @param str The value, as a String, to store in 102 the balance field. 103 */ 104 105 public void setBalance(String str) 106 { 107 balance = Double.parseDouble(str); 108 } 109 (Continued)
60
110 /** 111 The getBalance method returns the 112 account balance. 113 @return The value in the balance field. 114 */ 115 116 public double getBalance() 117 { 118 return balance; 119 } 120 }
61
Code Listing 6-21 (AccountTest.java)
1 import javax.swing.JOptionPane; // For the JOptionPane class 2 import java.text.DecimalFormat; // For the DecimalFormat class 3 4 /** 5 This program demonstrates the BankAccount class. 6 */ 7 8 public class AccountTest 9 { 10 public static void main(String[] args) 11 { 12 String input; 13 14 // Create a DecimalFormat object for displaying dollars. 15 DecimalFormat dollar = new DecimalFormat("#,###.00"); 16 17 // Get the starting balance. 18 input = JOptionPane.showInputDialog("What is your " + "account's starting balance?"); 20 22 BankAccount account = new BankAccount(input); (Continued)
62
23 24 // Get the amount of pay. 25 input = JOptionPane.showInputDialog("How much were " + "you paid this month? "); 27 28 // Deposit the user's pay into the account. 29 account.deposit(input); 30 31 // Display the new balance. 32 JOptionPane.showMessageDialog(null, "Your pay has been deposited.\n" + "Your current balance is $ " + dollar.format( account.getBalance()) ); 36 37 // Withdraw some cash from the account. 38 input = JOptionPane.showInputDialog("How much would " + "you like to withdraw? "); account.withdraw(input); 41 42 // Display the new balance 43 JOptionPane.showMessageDialog(null, "Now your balance is $" + dollar.format(account.getBalance()) ); (Continued)
63
(Continued) Code Listing 6-21 (AccountTest.java)
46 47 System.exit(0); 48 } 49 }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.