1. Trang chủ
  2. » Công Nghệ Thông Tin

Java Programming for absolute beginner- P9 doc

20 334 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 20
Dung lượng 419,61 KB

Nội dung

while (!gotValidNumber); System.out.println(“Your number is “ + inputNumber); } } The variables are reader, a BufferedReader, gotValidNumber, a Boolean value that tracks whether you got a valid integer from the users, and inputNumber, an int used to store the user’s input. In the try block, you try to read in the user’s input, parse it to an int, and assign it to inputNumber. You put this in a try block so that you can handle exceptions that occur, a NumberFormatException, or an IOExcep- tion . A NumberFormatException exception is thrown by the Integer.parseInt() method if its String argument is not a valid representation of an integer. If the users don’t enter a valid number, you catch the NumberFormatException excep- tion that is thrown and tell the users that they didn’t enter a valid number. You initialized gotValidNumber to false. If a NumberFormatException is thrown, the assignment gotValidNumber = true is never reached, so the loop continues to iterate. When the users finally do enter a valid number, gotValidNumber becomes true, the loop terminates, and you print the user’s number to show that you got a valid number. The output of this program is shown in Figure 4.11. In the InputChecker program, you had to initialize the inputNumber variable because it is assigned in a try block that might never work. If you don’t initialize the variable, you will get a compiler error. It will complain about the line where you print inputNumber. It will tell you that inputNumber might not be initialized. TRAP 118 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r FIGURE 4.11 The InputChecker program forces the users to enter a valid integer. Back to the NumberGuesser Program You’ve now learned everything you need to know to write the NumberGuesser pro- gram. It generates a random number, and then in a loop it continuously prompts the users for a number until they guess correctly. It also uses exception handling to make sure the users are entering valid numbers. Here is the source code list- ing for NumberGuesser.java: JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 118 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. /* * NumberGuesser * Picks a random number which the user must guess */ import java.io.*; import java.util.Random; public class NumberGuesser { public static void main(String args[]) { BufferedReader reader; Random rand = new Random(); int myNumber = rand.nextInt(100) + 1; int guess = -1; boolean invalid; int nGuesses = 0; reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println(“I’m thinking of a number between 1 and 100.”); System.out.println(“Can you guess what it is?”); do { nGuesses++; System.out.print(“Your guess: “); invalid = false; try { guess = Integer.parseInt(reader.readLine()); } catch (IOException ioe) { } catch (NumberFormatException nfe) { System.out.println(“That is not a valid Integer!”); guess = -1; invalid = true; } if (guess >= 1 && guess <= 100) { if (guess == myNumber) { System.out.println(“You guessed my number in “ + nGuesses + “ guesses!”); } else if (guess < myNumber) { System.out.println(“My number is HIGHER.”); } else { System.out.println(“My number is LOWER.”); } } else if (!invalid) { System.out.println(“Remember, my number is between “ + “1 and 100.”); } } while (guess != myNumber); } } 119 C h a p t e r 4 U s i n g L o o p s a n d E x c e p t i o n H a n d l i n g JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 119 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. You initialize reader, the BufferedReader used to read user input, rand, the Ran- dom object you use to generate random numbers, and guess, the user’s guess. You also have the variable myNumber, the random number that the users have to guess. nGuesses counts the number of times it takes the users to guess the correct num- ber. The boolean invalid variable tracks whether the user’s input is a valid int. In the do loop, you increment nGuesses, and prompt the users for a number. If the users don’t enter a valid number, you set guess to –1 and invalid to true. The reason you set guess to –1 is because it must have some value when it gets to the if statements that follow. You set it out of the range of possible numbers, so you don’t confuse your bogus value with an actual real value. The invalid variable eliminates the “ Remember, my number is between 1 and 100.” error message if the number isn’t valid; the users will get the “ That is not a valid integer!” error instead. The if-else structure determines whether the guess is correct, lower, higher, or out of range and tells the users in any of these cases. The while(guess != myNumber) loop condition keeps the loop iterating until the users guess the correct number. Try writing this program yourself. The output is similar to that shown in Figure 4.1. Summary In this chapter, you learned about loops and exception handling. You used for loops to count forwards and backwards. You used them to loop on arrays and nested for loops to loop on multidimensional arrays. You learned different ways to increment and decrement variables and how to skip values. You also learned about the while and do loops. You learned about exception handling and how to use it with loops to filter and get valid user input. In the next chapter, you learn all about object-oriented programming concepts and methods. 120 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r CHALLENGES 1. Write a for loop that counts from –100 to 100. 2. Write a program that allows the users to input an array’s size, and then prompts the users for all the values to put in that array, and finally prints them all. Make sure you use exception handling to get valid user input. 3. Write a while loop that generates random numbers between 1 and 100 and stops looping after it generates the same number twice. JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 120 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Object-oriented programming, OOP for short, is central in learning Java. Java is a strictly object-oriented program- ming language. In every Java program you’ve written thus far, you had to define a class. A class is more or less a tem- plate for an object. It defines what an object is and how it behaves. An instance of a class is called an object. In this chapter, you learn all about object-oriented programming concepts. You create a good amount of class definitions and learn to create and use instances of these classes. Ulti- mately, at the end of this chapter, you use these skills to cre- ate a text-based blackjack game. Before you move on to the later chapters of this book, make sure you understand the concepts in this chapter. The rest of the book assumes you understand the object-oriented programming concepts described herein. Venture onward! The main issues covered in this chapter are as follows: B l a c k j a c k: O b j e c t- O r i e n t e d P r o g r a m m i n g 5 CHAPTER JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 121 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. • Work with objects • Use member variables • Learn about access modifiers • Use methods • Understand encapsulation The Project: the BlackJack Application The project in this chapter is a simulation of a blackjack card game. If you’re not familiar with blackjack, here’s a brief explanation. The game consists of a dealer and at least one player. The game you create in this chapter will assume only one player. The goal of the game is to get a hand as close to 21 without going over. The dealer deals himself and the player two cards each. The dealer has one card face down and one face up, whereas the player has both cards face up. Each card has a specific point value. Cards 2 through 10 have the face value of the card regardless of suit. Picture (or face) cards (Jack, Queen, and King) all have point val- ues of 10. The Ace is a special case. The value of an Ace can be one or eleven, depending on which is more beneficial. The best possible hand, called a blackjack, consists of two cards totaling 21. This must be a 10-point card and an Ace. If either the dealer or the player has a black- jack, he or she instantly wins the hand, if they both have a blackjack, the game is a push (tie). Once the cards are dealt, the player has the option to hit (be dealt another card). The player’s goal is to come as close to 21 without going over, so players must be careful when hitting. If the players go over 21, they bust and lose the hand. When the players want to leave their hand as is, they are said to stand. When the players stand, the dealer reveals the hidden card and always hits if his hand is 16 or lower and always stands if it is 17 or higher, even when it is lower than the player’s score. If the players come closer to 21 than the dealer, they win. If they tie, again it is called a push. If the dealer is closer, the players lose. There are some more complicated rules that I didn’t include in the game for simplic- ity’s sake; these are the basic rules of blackjack. The BlackJack application uses an instance of a class, RandomCardDeck, which defines basically what a deck of cards does. Because Java is a object-oriented pro- 122 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 122 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. gramming language, BlackJack is a class itself. Towards the end of this chapter, you create these classes to develop the game. Figure 5.1 shows the output of a typ- ical session of the game. String objects represent the cards. The last character rep- resents the suit: C is for clubs, D is for diamonds, H is for hearts, and S is for spades. The dealer’s hidden card is represented by the String ??. 123 C h a p t e r 5 B l a c k j a c k: O b j e c t- O r i e n t e d P r o g r a m m i n g FIGURE 5.1 The player wins a hand of blackjack. Understanding Object-Oriented Concepts In this section, you create a simple class, SimpleCardDeck. You learn what instance variables and methods are and how they are part of class definitions. You also create an application that tests the SimpleCardDeck class, so you get a feel for how to create an object, access its members, and call its methods. The SimpleCardDeck Class The SimpleCardDeck class has a simple class definition. It is more or less just a demonstration of how to define a class. You’ve already defined classes in every Java program you’ve written, but you will notice a difference here: there is no main() method. This is because SimpleCardDeck is not an application; it’s a class definition that needs to be instantiated for its functionality. Here is the listing of SimpleCardDeck.java: /* * SimpleCardDeck * This class defines a simple deck of cards. */ public class SimpleCardDeck { //cards is a member variable String[] cards = {“2C”, “3C”, “4C”, “5C”, “6C”, “7C”, “8C”, “9C”, “10C”, “JC”, “QC”, “KC”, “AC”, “2D”, “3D”, “4D”, “5D”, “6D”, “7D”, “8D”, JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 123 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. “9D”, “10D”, “JD”, “QD”, “KD”, “AD”, “2H”, “3H”, “4H”, “5H”, “6H”, “7H”, “8H”, “9H”, “10H”, “JH”, “QH”, “KH”, “AH”, “2S”, “3S”, “4S”, “5S”, “6S”, “7S”, “8S”, “9S”, “10S”, “JS”, “QS”, “KS”, “AS”}; public void list() { for (int c=0; c < cards.length; c++) { System.out.print(cards[c] + “ “); } } } Try creating this class and compiling it. If you try to run it by using the java Sim- pleCardDeck command, it won’t work because there is no main() method. This further emphasizes the fact that this class is not an application. Go ahead and try it if you want to see what errors you will get. You create the SimpleCardDeck class here by using the class keyword and the class name. Now at this point, you’re used to defining the main() method. Instead you immediately declared cards, a string array. Because you declare this within the class definition (remember that the code within the curly braces is part of the class definition), it belongs to the SimpleCardDeck class. All Simple- CardDeck objects are instances of the SimpleCardDeck class and own their own cards variable. Another part of the class definition here is the list() method. You learn more about methods shortly, but even though you don’t know all about methods yet, you already have some familiarity with them. Creating the list() method is sim- ilar to creating the main() method. Similar to the cards member concept, this method is part of the class definition and is accessible to any SimpleCardDeck object. Basically, it just lists the contents of the object’s cards array. Learning About Objects Object-oriented programming is one of the most important programming con- cepts you can learn. Put simply, object-oriented programming is a way to orga- nize your programs so that they mimic the way things work in the real world. Objects in the real world are made up of smaller objects and interact with other objects. A ball, for example, is made up of a specific material that has its own properties and might be filled with air, or whatever. A person, another object, is made up of arms, legs, a head, and a torso, which are made up of skin, muscle, bone, which are made up of cells, and so on. The person can interact with the ball by throwing it or kicking it. These basic concepts are used to structure object-ori- ented programs. 124 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 124 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. For example, if you were programming a card game, which you are by the way, you write some sort of a class that defines a deck of cards and what can be done with it. Then in your game program, you create an instance of the class, a deck of cards object, and you can treat it like a deck of cards in your program. In turn, you can reuse that class in a different card game you write without needing to change the behavior of the card class. You only need to change the rules of the game, which resides in the game program itself. You know how to build a class definition. Now you learn how to create an instance of a class and reference its variables and methods. You created the Sim- pleCardDeck class. Here you write the SimpleCardDeckTest application that will create a SimpleCardDeck object and test it. Here is the source code listing for Sim- pleCardDeckTest.java : /* * SimpleCardDeckTest * Tests the use of the SimpleCardDeck class. */ public class SimpleCardDeckTest { public static void main(String args[]) { // create a new SimpleCardDeck object SimpleCardDeck deck = new SimpleCardDeck(); // access its member variable “cards” System.out.println(deck.cards[0]); System.out.println(deck.cards[10]); System.out.println(deck.cards[51]); // etc //Call its list() method deck.list(); } } Ah, something more familiar, a class with just a main() method. It’s the guts of main() that are interesting here. You declare and instantiate deck, a SimpleCard- Deck object in the line: SimpleCardDeck deck = new SimpleCardDeck(); You’ve done this before with BufferedReader and Random objects. The Simple- CardDeck deck segment of the statement declares deck to be a SimpleCardDeck object. The = new SimpleCardDeck() segment of the statement passes deck a ref- erence to a new SimpleCardDeck object, so at this point, deck contains a Simple- CardDeck object. Now that you have a SimpleCardDeck object, you can access its cards variable. To access an object’s variable (also called a field), you use dot notation to separate the 125 C h a p t e r 5 B l a c k j a c k: O b j e c t- O r i e n t e d P r o g r a m m i n g JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 125 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. object name from the field name (note that there are no spaces between the names): objectName.fieldName In the SimpleCardDeckTest program, you accessed the cards field and printed its contents: System.out.println(deck.cards[0]); You can’t directly access the field without the reference to the object. The object owns the field and must be accessed using the dot notation. The SimpleCard- DeckTest program can declare its own cards variable, which is separate from deck’s cards variable. You can see in the following code why dot notation is needed to specify which variable you are referencing: SimpleCardDeck deck = new SimpleCardDeck(); int cards = 52; //access my cards variable System.out.println(cards); //access deck’s cards variable System.out.println(deck.cards[0]); You also use dot notation to call the SimpleCardDeck’s list() method. When you call this method, it executes the statements defined within the method’s braces. The list() method simply loops through the cards array and lists all its con- tents. The syntax for calling an object’s method is as follows: objectInstance.instanceMethod(arguments); The line that calls deck’s list() method is as follows: deck.list(); It has no arguments, but the parentheses are required anyway. They differentiate methods from variables. Figure 5.2 shows the output of the SimpleCardDeckTest program. 126 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r FIGURE 5.2 The SimpleCard- DeckTest application uses a SimpleCardDeck object. JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 126 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Examining Member Variables In Chapter 2, you learned how to declare and use local variables. Local variables are declared within a method and are accessible only within that method. More specifically, they are accessible only within the block statement you declare them in. Class member variables are declared within the outer-most braces of the class definition, and are accessible to the class as a whole. Member variables are declared in almost the same way as local variables; in fact, so far, the only dif- ference is the location you declared them in. Member variables can be either instance variables or class variables. Instance vari- ables, such as cards variable from the SimpleCardDeck class, are owned by a par- ticular instance of the class. In the SimpleCardDeckTest program, deck is an instance of SimpleCardDeck and owns its own cards variable. If a second Simple- CardDeck object (deck2) is declared, it has its own cards variable and can manip- ulate it independently of deck’s version of the same variable. SimpleCardDeck deck2 = new SimpleCardDeck(); Class variables apply to the class and are not specific for each instance of the class. They are called static variables and I use the two terms interchangeably throughout the book. Oddly enough, the static keyword specifies that a variable is a class variable. The following ChristmasLight class definition declares an instance variable and a static variable. /* * ChristmasLight * Demonstrates static variables */ public class ChristmasLight { //color is an instance variable String color; //isLit is a static variable static boolean isLit; } The color variable is an instance variable, so each ChristmasLight object can store a different value in its own color variable. On the other hand, the isLit variable is a class variable and will hold only one value that must be shared by all instances of the ChristmasLight object. Wanna test it out? Of course you do! After all you know that you won’t remember any of this unless you do it for your- self, right? Here is the source listing for ChristmasLightTest.java: /* * ChristmasLightTest * Shows the effect of changing a static variable’s value */ 127 C h a p t e r 5 B l a c k j a c k: O b j e c t- O r i e n t e d P r o g r a m m i n g JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 127 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Blackjack: Object-Oriented Programming TRA Chapter 5 As you can see, there are two ways to access a static variable You can access it without a specific instance of the class by using the class name: JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 130 130 Java Programming for the Absolute. .. as a benefit Employee.MALE and Employee.FEMALE are class constants The characters that represent these states never change Here is the source code listing for EmployeeTest .java: JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 132 Java Programming for the Absolute Beginner 132 jack.sex is not a constant, as you know, but is an instance variable You know that it should logically only have one of two values,...JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 128 128 Java Programming for the Absolute Beginner public class ChristmasLightTest { public static void main(String args[]) { ChristmasLight[] lights = { new ChristmasLight(), new ChristmasLight(),... explain in greater detail what methods are, how to define them, and how to invoke them I also explain how to return values from methods and how to pass them parameters JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 134 134 Java Programming for the Absolute Beginner else { running = false; System.out.println(“The automobile has been shut off.”); } } public String getColor() { return color; } public void setColor(String... Chapter 5 public static void main(String args[]) { Automobile auto1 = new Automobile(); System.out.println(“Auto 1: “ + auto1.toString()); JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 136 136 Java Programming for the Absolute Beginner Declaring a Method In order to declare a method, you must define it within the class source file The method declaration includes the method signature, which includes any... even days debugging your code before you realize that, although you meant to change the state of only one of your instances, you were unintentionally changing them all As a rule of thumb, always reference class variables through the class name Field Modifiers Field modifiers are keywords that you place before variable names to specify the characteristics of the variables For example, the static keyword... methods as lines of Java code that execute when you tell them to You define methods in a separate section of your program and give it a name so that you can tell it to run from another method, such as main, by using the name you gave it You have already TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-05.qxd... in the output shown in Figure 5.3, all instances of the ChristmasLight class always share one value for their isLit variable FIGURE 5.3 One light goes out, they all go out! TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-05.qxd 2/25/03 8:51 AM Page 129 129 ChristmasLight.isLit = false; You can also access... Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Blackjack: Object-Oriented Programming System.out.println(“Driving Auto 1 ”); auto1.drive(); System.out.println(“Driving Auto 2 ”); auto2.drive(); Chapter 5 public static void main(String args[]) { Automobile auto1 = new Automobile(); System.out.println(“Auto 1: “ + auto1.toString()); JavaProgAbsBeg-05.qxd... instance variables, class variables, and constants The EmployeeTest program demonstrates the different behavior of these variables and emphasizes exactly what the field modifiers are used for Here is the source code for Employee .java: /* * Employee * This class demonstrates the use of member variables */ public class Employee { String name; int age; char sex; String position; double payRate; static int vacationDays; . remove this watermark. Object-oriented programming, OOP for short, is central in learning Java. Java is a strictly object-oriented program- ming language. In every Java program you’ve written thus far,. users for a number until they guess correctly. It also uses exception handling to make sure the users are entering valid numbers. Here is the source code list- ing for NumberGuesser .java: JavaProgAbsBeg-04.qxd. represent the cards. The last character rep- resents the suit: C is for clubs, D is for diamonds, H is for hearts, and S is for spades. The dealer’s hidden card is represented by the String ??. 123 C h a p t e r

Ngày đăng: 03/07/2014, 05:20

TỪ KHÓA LIÊN QUAN