TAILIEUCHUNG - Java Programming for absolute beginner- P9

Java Programming for absolute beginner- P9:Hello and welcome to Java Programming for the Absolute Beginner. You probably already have a good understanding of how to use your computer. These days it’s hard to find someone who doesn’t, given the importance of computers in today’s world. Learning to control your computer intimately is what will separate you from the pack! By reading this book, you learn how to accomplish just that through the magic of programming. | 2 25 03 8 50 AM Page 118 k 0 c c 0 2 V 0 a c S S s k a o k Q. S s while IgotValidNumber 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 lOExcep-tion. A NumberFormatException exception is thrown by the 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 exception 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 gotVal idNumber 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 . 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. figure 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 program. 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 .

TỪ KHÓA LIÊN QUAN