Java Programming for absolute beginner- P4 ppt

20 426 0
Java Programming for absolute beginner- P4 ppt

Đ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

//The value of b will be 1. //The addition happens first because of the parentheses //Next the division and then the subtraction. int b = 10 - (4 + 14) / 2; System.out.println(“10 - (4 + 14) / 2 = “ + b); //The value of c will be -1 int c = 10 - (4 + 14 / 2); System.out.println(“10 - (4 + 14 / 2) = “ + c); } } 38 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 2.5 This demonstrates how parentheses affect operator precedence. Getting Simple User Input Thus far, the programs you have written have been one-sided in that they per- form specific tasks and do not accept any user input. Every time you run these programs the output is exactly the same, making them all but useless in the eyes of a user after the first few times they are run. How can you make procedures more dynamic? By adding the functionality to accept and use user input. Any- time the user runs the application, he or she can enter different input, causing the program to have the capability to have different output each time it is run. Because programmers write programs in the real world to be useful to users, this almost always means that the programs provide some interface that accepts user input. The program then processes that input and spits out the result. Accepting command-line input is a simple way to allow users to interact with your pro- grams. In this section, you will learn how to accept and incorporate user input into your Java programs. What follows is a listing of the HelloUser application: JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 38 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. /* * HelloUser * Demonstrates simple I/O */ import java.io.*; public class HelloUser { public static void main(String args[]) { String name; BufferedReader reader; reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print(“\nWhat is your name? “); try { name = reader.readLine(); System.out.println(“Hello, “ + name + “!”); } catch (IOException ioe) { System.out.println(“I/O Exception Occurred”); } } } As you can see in Figure 2.6, the program prints a message asking for the user’s name. After that the cursor blinks awaiting user input. In Figure 2.7 you see that the user entered her name, “Roseanne” and the application read it in and then printed “Hello, Roseanne!” 39 C h a p t e r 2 V a r i a b l e s, D a t a T y p e s ,a n d S i m p l e I / O FIGURE 2.6 The user is prompted for his or her name, which is accepted through standard input. JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 39 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Using the BufferedReader Class Unfortunately, getting simple user input is not very straightforward. One might think it would make sense that the syntax for reading a line would be as simple as writing a line of output. However, this is not the case. As you know, writing standard output can be done like this: System.out.println(“Shampoo is better!”); So, it would be natural to think reading input could be done like this: System.in.readln(); But it is not that simple. First you must import the java.io package, which pro- vides functionality for system input and output: import java.io.*; A package is a group of complimentary classes that work together to provide a larger scale of functionality. This is the second Java program you’ve written that uses the import statement. In the HelloWeb applet from Chapter 1, you imported the java.awt.Graphics class, which is part of the java.awt package. The differ- ence here is that you use an asterisk to signify that you might be interested in all the classes that the java.io package groups together. Basically, you are import- ing the java.io package here to give your program the capability to call upon the I/O functionality. Specifically, it allows you to use the BufferedReader and Input- StreamReader classes in your program. At this point, you don’t need to under- stand anything about these classes except that InputStreamReader reads the user’s input and BufferedReader buffers the input to make it work more effi- ciently. You can think of a buffer as sort of a middle man. I hear the Corleone family had a lot of buffers. When reading data in, a program has to make a system call, which can take a relatively long time (in computer-processing terms). To make up for this, the buffering trick is used. Instead of making a system call each time you 40 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 2.7 The program says hello to the user after she enters her name. JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 40 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. need a piece of data, the buffer temporarily stores a chunk of data before you ask for it using only one system call. The buffer is then used to get data for subse- quent requests because accessing memory is much faster than using a bunch of system calls. Inside the main() method, you declared two variables: String name; BufferedReader reader; Neither of them is a primitive data type. They are both instances of classes. The name variable is declared to be a String, giving it the capability to hold strings, which are covered in the next section, and reader is declared to be a Buffere- dReader , giving it the functionality to buffer input. The next line basically speci- fies reader to be a standard input buffer: reader = new BufferedReader(new InputStreamReader(System.in)); In this program you used a slightly different approach to printing a line of output. You used the System.out.print() method instead of the System.out.print- ln() method. What’s the difference? The System.out.println() method prints a message to the screen and then adds a carriage return to the end of it. The System.out.print() method does not add a carriage return to the end of the output line. As you see in Figures 2.6 and 2.7, the computer prompts the user for his or her name and the user types the name on the same line as the prompt. It is also important to note that you used a newline character escape code \n within the string passed to System.out.print() method. This moves the cursor down one line before printing the message. After you have instantiated the BufferedReader object, which you have stored in the reader variable, it can be used to accept user input. This line of code is what prompts the user. name = reader.readLine(); Confused? That’s okay if you are. The important thing here is that you learn the syntax for accepting user input. Bear with me, this concept, as well as others, become clearer later on. You’ll use this method of obtaining simple user input in these early chapters to create command prompt-based games until you learn graphic user interface (GUI) programming later. Handling the Exceptions Although exception handling is covered in more detail later in this book, I feel that I should explain the basics of it here because you are required to handle exceptions in this application. Exceptions are encountered when code does not HINT 41 C h a p t e r 2 V a r i a b l e s, D a t a T y p e s ,a n d S i m p l e I / O JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 41 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. work as it is expected to. Exception handling is used to plan a course of action in the event your code does not work as you expect it to. Here is an analogy to help you digest this concept. You have to go to work or school every normal weekday, right? Well, what if there is a blizzard or a tornado and you cannot go to work? In this analogy, the blizzard or tornado is the exception because it is an abnor- mality. The way this exception is handled is that you end up staying home from work. Java requires that exceptions be handled in certain situations. In the HelloUser application, you are required to handle an IOException (input/output exception). What if you never actually get the user’s input here? This would be an exception and you would not be able to incorporate the user’s name in the program’s out- put. In the case of this application, you issue an error message, indicating that an exception was encountered. You do not say “Hello” to the user—you can’t because you were not able to retrieve the user’s name. You handled exceptions in the HelloUser application by using the try…catch structure. Any code, such as reading user input that might cause an exception, is placed within the try block, or “clause”. Remember that a block is one or more statements enclosed within a set of curly braces: try { name = reader.readLine(); System.out.println(“Hello, “ + name + “!”); } Here, you are trying to read user input and use it in a standard output line. What if it doesn’t work? That’s what the catch clause is for: catch (IOException ioe) { System.out.println(“I/O Exception Occurred”); } If the code within the try clause does not work as it is expected to—there is an IOException— the code within the catch clause is executed. In this case the error message “I/O Exception Occurred” is printed to standard output to let the users know that a problem was encountered. In the real world, you try to handle exceptions as gracefully as you can. When detecting exceptions, you should try to handle them in a way so that your program uses default values instead of halt- ing abruptly, but in some instances, your program just can’t continue due to some error that you can’t provide a work-around for. In these cases, you should at the very least, try to generate meaningful error messages so that users can use them to resolve any possible problems on their end. 42 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-02.qxd 2/25/03 8:13 AM Page 42 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The Math Game In this section you incorporate much of what you’ve learned so far into a single application. After you write and compile this application, you can actually use it as a tool to remind yourself how arithmetic operators work in Java. Here is a list- ing of the source code for MathGame.java: /* * MathGame * Demonstrates integer math using arithmetic operators */ import java.io.*; public class MathGame { public static void main(String args[]) { int num1, num2; BufferedReader reader; reader = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print(“\nFirst Number: “); num1 = Integer.parseInt(reader.readLine()); System.out.print(“Second Number: “); num2 = Integer.parseInt(reader.readLine()); reader.close(); } // Simple Exception Handling catch (IOException ioe) { System.out.println(“I/O Error Occurred, using 1 ”); num1 = num2 = 1; } catch (NumberFormatException nfe) { System.out.println(“Number format incorrect, using 1 ”); num1 = num2 = 1; } //Avoid this pitfall e.g. 1 + 1 = 11: //System.out.println(num1 + “ + “ + num2 + “ = “ + num1 + num2); System.out.println(num1 + “ + “ + num2 + “ = “ + (num1 + num2)); System.out.println(num1 + “ - “ + num2 + “ = “ + (num1 - num2)); System.out.println(num1 + “ * “ + num2 + “ = “ + (num1 * num2)); System.out.println(num1 + “ / “ + num2 + “ = “ + (num1 / num2)); System.out.println(num1 + “ % “ + num2 + “ = “ + (num1 % num2)); } } 43 C h a p t e r 2 V a r i a b l e s, D a t a T y p e s ,a n d S i m p l e I / O JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 43 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Parsing Strings to Numbers Most of the code in the MathGame application should already be familiar to you. The code that is new to you is the code that parses a string value into an integer value: Integer.parseInt(reader.readLine()); Parsing, just like casting, is changing the data type of the value of a variable or lit- eral. The BufferedReader.readLine() method accepts the users input in string form. You cannot assign strings to int variables or perform mathematical opera- tions on them, so you must first convert them to numbers. For instance, you can’t do this: int myNumber = “8”; An int variable can only store a valid int value, but in the line above “8” is expressed as a String literal, not an int. Because you need to accept user input here in string form, you need a way to parse the String input to an int. Inte- ger.parseInt() does this. It is a method defined within the Integer class. It accepts a String argument and returns the int value of that string. For example if the String literal “8” is passed to this method, it returns the int 8. Here are some useful methods for converting strings to numbers: Byte.parseByte(String s) Converts a string to a byte. Short.parseShort(String s) Converts a string to a short. Integer.parseInt(String s) Converts a string to an int. Long.parseLong(String s) Converts a string to a long. As shown in Figure 2.8, this program prompts the user for two integers and then performs arithmetic operations on them. It displays the results of these opera- tions to the user. It’s not exactly a game, unless math is fun for you, but you get the point. 44 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 2.8 The MathGame application demonstrates mathematical operations applied to integers. JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 44 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 45 C h a p t e r 2 V a r i a b l e s, D a t a T y p e s ,a n d S i m p l e I / O Float.parseFloat(String s) Converts a string to a float. Double.parseDouble(String s) Converts a string to a double. The string passed to a method that parses it to another data type must be a valid representation of that data type. For example, if you tried to parse the String “one” to an integer using Integer.parseInt(), it would cause a NumberFormatException, however, it is not required that you handle this excep- tion, although you do in the MathGame application by simply using the int 1 if user input isn’t obtained. If you don’t handle the NumberFormatException, your program will crash if the user types a value that cannot be parsed to an int. The TipCalculator Application Here is another program for you to take a look at. It uses concepts of the Math- Game and TipAdder applications. It prompts the user for the price of the meal, converts the String value of the user’s input into a double and then calculates the tip and displays the information to the user. Take a look at the source code: /* * TipCalculator * Parses user input and does floating point math */ import java.io.*; public class TipCalculator { public static void main(String args[]) { String costResponse; double meal, tip, total; BufferedReader reader; reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print(“\nHow much was the meal? “); try { costResponse = reader.readLine(); // Note: we are not handling NumberFormatException meal = Double.parseDouble(costResponse); tip = meal * 0.15; total = meal + tip; System.out.println(“The meal costs $” + meal); System.out.println(“The 15% tip is $” + tip); System.out.println(“The total is $” + total); reader.close(); } TRAP JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 45 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. catch (IOException ioe) { System.out.println(“I/O Exception Occurred”); } } } Figure 2.9 shows the output of this program. Notice that this calculation is more precise than in the TipAdder program. That’s because you used doubles instead of floats. Oh, one more thing, you didn’t handle any of the exceptions. Figure 2.10 shows what happens when you don’t get the double value you expect. 46 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 2.9 The output of the TipCalculator application. FIGURE 2.10 Oops, my program crashed! I didn’t type a valid double value. Accepting Command-Line Arguments As mentioned in Chapter 1, it is possible to pass command-line arguments to your application. Command-line arguments are parameters that are passed to the program when it is initially started up. This is done, as you’d imagine, from the JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 46 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. command prompt. You pass parameters to an application by using the following syntax when running the application: java ApplicationName command_line_arguments When using a Macintosh, you will be prompted for any command-line arguments when you run your application. Command-line arguments are passed to the main() method as its only parameter: String args[]. It is an array (list) of para- meters, so you can handle it like any other array. You learn about arrays in the next chapter. For now, you can just write the following application to give your- self a basic idea of how Java can accept and use command-line arguments. /* * HelloArg * Uses command-line arguments */ public class HelloArg { public static void main(String args[]) { System.out.println(“Hello, “ + args[0] + “!”); } } As you can see in Figure 2.11, I ran this procedure three times using different command-line arguments causing the application to issue different output. By the way, I wouldn’t make the last guy angry, you wouldn’t like him very much if he gets angry. 47 C h a p t e r 2 V a r i a b l e s, D a t a T y p e s ,a n d S i m p l e I / O INTHEREAL WORLD Command-line arguments are used for a number of different purposes in the real world. They are used as parameters that affect the way the program runs. Command-line arguments can exist to allow the user certain options while run- ning your program. One other major use of command-line arguments from a programmer’s standpoint is to aid in debugging or testing your code. You can use a command-line argument to set some sort of debug-mode parameter. With this debug mode set, you can debug your code by giving yourself special options that would not normally be available. For example, say you are a video game programmer. You need to test a particular game level, but it is a particu- larly difficult level for you to get through or would be time consuming. You can use a command-line argument that gives you access to any position in any level of the game you’re programming, so you can just test the parts you need to. JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 47 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... methods for examining and operating on its individual characters It also has methods for searching strings, for comparing them, concatenating them (appending one string to another), for extracting substrings (smaller segments of strings) and for converting alphabetical characters from uppercase to lowercase (or visa versa) It also has methods for converting other data types into string values Java treats... of the chapter and have already learned so much about the Java language, TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Variables, Data Types, and Simple I/O char strChar = str.charAt(4); JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 50 50 Java Programming for the Absolute Beginner TA B L E 2 6 S O M E S TRING C L A S S... your name?”); System.out.println(“Bye!”); } } TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Variables, Data Types, and Simple I/O String initials; Chapter 2 public class NameGame { JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 52 Java Programming for the Absolute Beginner 52 When you run this program it should look similar... test for You learn about arrays and understand how to use them in your Java programs Arrays are used in real-world programming to collect data of a single type together in a list For example, say you’re writing a retail cash register program You would want to keep TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-03.qxd...JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 48 Java Programming for the Absolute Beginner 48 FIGURE 2.11 Passing commandline arguments to the HelloArg application TRA P Arguments are separated by spaces Make sure that if an argument needs... Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 56 Java Programming for the Absolute Beginner 56 track of the purchase item prices separately so you could print them all out as individual lines on the receipt It would be ridiculous to have an instance variable for each item, right? Instead, you could store all of the prices in a list by using a double type... Math.random() and java. util.Random • Use the if statement • Use the switch statement • Use the ternary operator (? :) • Declare, initialize, and iterate arrays The Project: the Fortune Teller The final project of this chapter is the FortuneTeller application You can see the final project in Figure 3.1 FIGURE 3.1 The Great Randini predicts tomorrow When you run this application, your fortune is read for tomorrow... applications You learned how to handle numerical values in Java and perform arithmetic operations on them You were also introduced to some more advanced topics such as event handling and object-oriented programming Don’t worry if you don’t understand it all yet It’s a lot to absorb You will continue to build upon what you already know about Java in the chapters to come In the next chapter, you learn... literals as String objects String literals are always surrounded by quotation marks That’s how Java knows they’re strings and not variable names or some other Java code An object is an instance of a particular class Any operations that you can perform with String objects stored in variables can also be performed with String literals Here is an example using the String.charAt() method This method will... fullName.charAt(fullName.length() – 1) You get the TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 53 53 Summary 1 Write an application that calculates a 5% tax for any given price and displays the total cost 2 Write an application that prints the multiplication table for integers 1 through 12 3 Write an application . arithmetic operators work in Java. Here is a list- ing of the source code for MathGame .java: /* * MathGame * Demonstrates integer math using arithmetic operators */ import java. io.*; public class. methods for examining and operating on its individual characters. It also has methods for searching strings, for comparing them, concatenating them (appending one string to another), for extracting. you can test for. You learn about arrays and understand how to use them in your Java programs. Arrays are used in real-world programming to collect data of a single type together in a list. For example,

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

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan