630 likes | 643 Views
Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 6. 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
E N D
Starting Out with Java:From Control Structures through Objects • 5th edition • By Tony Gaddis • Source Code: Chapter 6
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)
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
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 privatedouble 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 }
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 " + 16 "to the setLength method."); 17 • // Call the box object's setLength method. 19 box.setLength(10.0); (Continued)
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.
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)
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 }
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)
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 returnlength; 42 } 43 (Continued)
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 returnwidth; 53 } 54 }
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)
// Display the object's length and width. 22 System.out.println("The box's length is " + 23 box.getLength()); 24 System.out.println("The box's width is " + 25 box.getWidth()); 26 } 27 } Program Output The box's length is 10.0 The box's width is 20.0
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)
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 returnlength; 42 } 43 (Continued)
44 /** 45 The getWidthmethod 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 returnlength *width; 64 } 65 }
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 Rectanglebox = newRectangle(); 13 15 box.setLength(10.0); 16 box.setWidth(20.0); 17 • // Display the length. 19 System.out.println("The box's length is " + 20 box.getLength()); (Continued)
21 • // Display the width. 23 System.out.println("The box's width is " + 24 box.getWidth()); 25 • // Display the area. 27 System.out.println("The box's area is " + 28 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
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 16 // Create three Rectangle objects. 17 Rectangle kitchen = new Rectangle(); 18 Rectangle bedroom = new Rectangle(); 19 Rectangle den = new Rectangle(); 20 (Continued)
22 input = JOptionPane.showInputDialog("What is the " + 23 "kitchen's length?"); 24 number = Double.parseDouble(input); • kitchen.setLength(number); 26 input = JOptionPane.showInputDialog("What is the " + 27 "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 " + 33 "bedroom's length?"); 34 number = Double.parseDouble(input); • bedroom.setLength(number); 36 input = JOptionPane.showInputDialog("What is the " + 37 "bedroom's width?"); 38 number = Double.parseDouble(input); 39 bedroom.setWidth(number); 40 (Continued)
42 input = JOptionPane.showInputDialog("What is the " + 43 "den's length?"); 44 number = Double.parseDouble(input); 45 den.setLength(number); 46 input = JOptionPane.showInputDialog("What is the " + 47 "den's width?"); 48 number = Double.parseDouble(input); 49 den.setWidth(number); 52 totalArea = kitchen.getArea() + bedroom.getArea() 53 + den.getArea(); 54 56 JOptionPane.showMessageDialog(null, " + "The total area” + 57 "of the rooms is " + totalArea); 58 59 System.exit(0); 60 } 61 }
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.
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 voidmain(String[] args) 9 { 10 // Create a Rectangle object, passing 5.0 and • // 15.0 as arguments to the constructor. 12 Rectanglebox = new Rectangle( 5.0, 15.0 ); 13 14 // Display the length. 15 System.out.println("The box's length is " + 16 box.getLength()); 17 18 // Display the width. 19 System.out.println("The box's width is " + 20 box.getWidth()); 21 (Continued)
22 // Display the area. 23 System.out.println("The box's area is " + 24 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
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 { 21manufact = man; 22 model = mod; 23 retailPrice = price; (Continued)
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)
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 returnmanufact; 67 } 68 (Continued)
69 /** 70 getModel method 71 @return The phone's model number. 72 */ 73 74 public String getModel() 75 { 76 returnmodel; 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 }
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 voidmain(String[] args) 11 { 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)
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(); 30 // Create an instance of the CellPhone class, 31 32 34 CellPhonephone =newCellPhone( 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)
Program Output with Example Input Shown in Bold Enter the manufacturer: Acme Electronics [ Enter ] Enter the model number: M1000 [ Enter ] Enter the retail price: 199.99 [ Enter ] Here is the data that you provided: Manufacturer: Acme Electronics Model number: M1000 Retail price: $199.99
Code Listing 6-14 (Die.java) 1 import java.util.Random; 2 3 /** 4 The Die class simulates a six-sided die. 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 constructorperforms an initial 14 roll of the die. 15 @param numSides The number of sides for this die. 16 */ 17 18publicDie( int numSides ) 19 { 20 sides = numSides; 21 roll(); // What are we calling? 22 } 23 (Continued)
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 returnsides; // What is sides? 46 } (Continued)
47 48 /** 49 getValue method 50 @return The value of the die. 51 */ 52 53 public int getValue() 54 { 55 returnvalue; 56 } 57 } End Class
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 12 13 // Create two instances of the Die class. 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 " + 19 DIE1_SIDES + " sided die and a " + 20 DIE2_SIDES + " sided die."); 21 22 System.out.println("Initial value of the dice:"); 23 System.out.println( die1.getValue() + " " + die2.getValue() ); (Continued)
24 • // 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 } 38 } 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
Code Listing 6-16 (DieArgument.java) 1 /** 2 This program rolls a 6-sided die and 3a 20-sided 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 DiesixDie = new Die(SIX_SIDES); 15 16 17 DietwentyDie = new Die(TWENTY_SIDES); 18 • // Roll the dice. 20 rollDie(sixDie); 21 rollDie(twentyDie); // Passing a Reference as an Argument 22 } (Continued)
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() + 34 " 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
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)
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 StringgetChoOrHan() 45 { 46 String result; // To hold the result (Continued)
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)
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 { 80 return die2Value; 81 } 82 }
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)
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 36 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)
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)
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 }
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)
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)
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, 57 Player player2 ) 58 { 59 // Show the dice values. 60 System.out.printf("The dealer rolled %d and %d.\n", 61 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)
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)