0% found this document useful (0 votes)
29 views

Chapter05 Lab MurachBook

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
29 views

Chapter05 Lab MurachBook

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 102
How to use classes and methods This chapter shows you how to write a complete Java application that gets input from a user, makes a calculation, formats the output, and displays it to the user. This teaches you how to use some of the classes and methods that are available from the Java API. When you finish this chapter, you should be able to write comparable applications of your own. How to work with classes, objects, and methods... How to import classe. How to create an object How to call a method from an object. How to call a method from a cass. How to view the documentation forthe Java API How to work with the console How to use the Scanner class to get input. How to conver strings to number. ‘A class that reads input from the consol How to convert numbers to formatted strings A class that prints formatted numbers tothe console How to code simple control statements. How to compare numbers, How to compare strings How to code a while loop How to code an iffelse statement. The Line Item application ‘The user interface ‘The code, The Future Value application ‘The user interface. ‘The code Perspective BEeSaRsaaee 64 Section 1 Get started right How to work with classes, objects, and methods In the previous chapter, you leamed how to ereate String objects from the String class in the Java API. As you develop Java applications, though, you need to use dozens of different Java classes. To do that, you need to know how to create objects from Java classes, how to call Java methods, and how to import Java classes. How to import classes The Java SE API stores related classes in packages. Figure 3-1 begins by summarizing three commonly used packages. The java.lang package contains the lasses (stich as the String class) that are fundamental to the Tava language. Asa result, this package is automatically available to all Java code. However, if you want to use a class from a package other than java.lang, you can include an import statement for that class at the beginning of the current ‘lass. If you don’t, you can still use the class, but you have to qualify it with the name of the package that contains it each time you refer to it. Since that can lead to a lot of unnecessary typing, most programmers code import statements for the classes they use. When you code an import statement, you can import a single class by specifying the class name, or you can import all of the classes in the package by typing an asterisk (*) in place of the class name. In this figure, for example, the first import statement imports the Scanner class Ut’s in the java.util package. On the other hand, the second import statement imports all of the classes in the java.util package including the Scanner class. However, this only imports all classes in the java.util package, not any classes from other packages that begin with java.util such as java.util.regex. Although it requires less code to import all of the classes in a package at once, importing one class at a time provides a couple benefits. First, it clearly identifies the classes that your code uses, which ean be helpful to other program- mers who review your code, Second, it helps avoid ambiguous references to classes. For example, the Date class exists in both the java.util and java.sql packages. As a result, if you import all classes from both packages and attempt to use the Date class, the compiler doesn’t know which Date class you want to use. Chapter 3 How to use classes and methods Common packages ECC od Java.lang Classes that are fundamental to the Java language, including classes that work with primitive data types and strings. java.util Utility classes, including those for getting input from the console Java.text (Classes that handle text, including those that format numbers and dates. Common classes Java.lang.string Java.lang. Integer Java. text .NumberFormat The syntax of the import statement For a single class Amport packagenane.ClassNam For all classes in the package import packagename.*7 How to import the Scanner class For the Scanner class only import java-util.scanner; For all classes in the java.util package Amport java.util.*; Code that uses the Scanner class If it has been imported Scanner ec = new Scanner(System.in); If it has not been imported Java.util.scanner sc = new Java.util.scanner(System.in); Description ‘© The API for the Java SE provides a large library of classes that are organized into packages. ‘© Allclasses stored in the java.lang package are automatically available to all Java code. ‘+ To use classes that aren’t in the java.lang package, you can code an import state~ ‘ment. To import one class, specify the package name followed by the class name, To import all classes in a package, specify the package name followed by an asterisk (*). Figure 3-1 How to import classes 65 66 — Section |Get started right How to create an object from a class To use a Java class, you typically start by creating an object from a Java class. As the syntax in figure 3-2 shows, you do that by coding the new keyword, and the name of the Java class followed by a set of parentheses. These paren- theses call the constructor of the class, which is a special block of code that creates the object from the class and initializes it. Within the parentheses, you code any arguments that are required by the constructor. In most cases, you assign the object that’s created by the constructor to a variable. That way, you can use it later. In the first example, the code assigns the Scanner object that's created to a Scanner variable named se. Here, the constructor for this object requites one argument, the System.in object. This object represents console input and is created by Java automatically. As a result, you can use this object to get console input, Although this constructor requires only one argument, some constructors require zero arguments and some require two or more arguments. You'll learn ‘more about how this works as you go through this book. When you create an object, you can think of the class as the template for the object. That’s why the object can be called an instance of the class, and the process of creating the object can be called instantiation, Whenever necessary, you can create multiple objects from a class. For instance, you often use multiple String objects in a single block of code even though there is only one String class. How to call a method from an object Once you create an object from a class, you can call the methods of the object. A method is a block of code that performs an action. In addition, a method typically returns a value or object that you ean assign to a variable ‘To call a method from an object, you code the object name, a dot (.), and the ‘method name followed by a set of parentheses. Within the parentheses, you code the arguments that are required by the method. In the second example, the statement calls the nextLine method of the Scanner object named sc to get the current line of text from the console. This ‘method doesn’t require an argument. As a result, it’s followed by an empty set of parentheses. This method returns a String object, and this example assigns it to the String variable named line. How to call a method from a class Besides the regular methods that you can call from an object, some classes provide static methods. Static methods are similar to regular methods, but you can call them directly from the class without creating an object from the class. In the third example, the statement calls the static parseDouble method of the Double class. This method requires one argument, AS a result, this example specifies the argument within the parentheses that come after the method name, Chapter 3 How to use classes and methods 67 How to create an object from a class Syntax new ClassName (arguments)? Example Scanner sc = new Scanner(System.in); — // ox a Scanner object named sc How to call a method from an object Syntax objectiane .nethodNane (arguments) Example String line = sc.nexeLine(); // get a string opject trom the console How to call a static method from a class Syntax ClassName methodName (arguments) Example double price Double.parseDouble(line); // convert a String to a double Description When you create an object from a Java class, you are creating an instance of the class. Then, you can use the methods of the class by calling them from the object. ‘© Some Java classes contain static methods. You can call these methods directly from the class without creating an object. © When you create an object from a class, the constructor may require one or more arguments. These arguments must have the required data types. If there are multiple arguments, you must code them in the correct sequence, and you must separate each argument with a comma. ‘© When you call a method from an object or a class, the method may require one or ‘more arguments. Here again, these arguments must have the required data types. If there are multiple arguments, you must code them in the correct sequence, and you ‘must separate each argument with a comma, ‘* When you call a method from an object ora class, the method may return a primitive value or an object. If you want to use this data, you can assign the primitive value or object to a variable. Figure 3-2 How to work with classes, objects, and methods Section 1 Get started right Here, the argument is the String variable named line created in the second example. This method returns a double value, and this example assigns it to the double variable named price. As you read this book, you'll learn how to use dozens of classes and methods. For now, though, you just need to focus on the syntax for creating an object from a class, for calling a method from an object, and for calling a static method from a class. How to view the documentation for the Java API One of the most difficult aspects of using Java is learning how to use the classes and methods that your applications require. To do that, you frequently need to study the API documentation that comes with Java, Figure 3-3 summarizes some of the basic techniques for navigating through the API documentation. This figure shows the start of the documentation for the Scanner class, which goes on for many pages. To display the documentation for a class, you can click the package name in the upper left frame. Then, you can click the class name in the lower left frame, IF you scroll through the documentation for the Scanner class, you'll get an idea of the amount of the documentation that’s available. After a few pages of descriptive information, you come to a summary of the eight constructors for the class, After that, you come to a summary af dozens of methods of the class. That's followed by more detail about the constructors, which is followed by ‘more detail about the methods. For a beginning programmer, this is too much information, That’s why one Of the goals of this book is to introduce you to a subset of classes and methods that you'll use in most of the applications that you develop. Once you've learned how to use those classes and methods, the API documentation should make ‘more sense to you. and you should be able to use that documentation to research classes and methods that aren't presented in this book. However, it’s never too early to start using the documentation, So, feel free to use the documentation to learn more about the classes and methods presented in this book. After you learn how (0 use the Scanner class, for example, use the API documentation to lear more about that class. Chapter 3 How to use classes and methods The documentation for the Scanner class Eisenia Paton ss © 2S Bittpsiidocsoracecomijavase/¥dos/apl sat concaect SUMMARY NESTED | FELD |CONSTR|METHCO DETAR: FLD | CONSTR | METHOD Jovecetuncton java.ut sas se Class Scanner ‘Ontong | Java lang Object roe va tl Seaneer Froperyfermszon asl implemente icaraces: overytesocedune Closeable, AutoCloseable, Iteratorestring> public fina class scaner Extends oject ftplenents Teratorestring, closeabte Sper searcomstso | cpl tet scanner wich can pare primitive types and stings sng regular Greater Than Returns a true value if lft operand is greater than right operand, < Less Than ‘Returns a true value if left operand is less than the right operand. > Greater Than Or Equal Retums a true value if left operand is greater than or equal to right operand, « Less Than Or Equal __Retums atrue value if left operandi less than or equal to right operand. Code that uses relational operators months == 3 // equal to a numeric literal years != 0 7/ not equal to a numeric literal @iscountPercent > 2.3 // greater than a numeric literal i < months 7/ less than a numeric variable subtotal >= 500 // greater than or equal to a numeric literal quantity <= reorderroint —// less than or equal to a numeric variable Acommon error when testing numbers for equality months = 3 1/ this does not test for equality! Two methods of the String class Een equals (string) Compares the value ofthe String object with a String angument and retums a true value if they are equal ora false value if they are not equal. This method makes a case-sensitive comparison equalsignorecase(String) Works like the equals method but is not case-sensitive. Code that uses the methods of the String class e-equals (*y") 7/ equal to a string literal ice.equalsgnorecase("y") 7/ equal to a string literal jthame -equais("Jones")) 7/ noe equal to a string litera fequalstgnorecase(productcede) // equal to another string variable Two common errors when testing strings for equality choice = *y" 71 thie does not test for equality! choice == "y" 7/ this does not test for equality! Description + A Boolean expression is an expression that evaluates to either tue or false. © You can use the relational operators to compare two numeric operands and return a Boolean value that is either true or false. ‘+ To test two strings for equality, you must call one of the methods of the String class. The equality operator (==) does not test two strings for equality. Figure 3-9 How to compare numbers and strings 82 Section |Get started right How to code a while loop Figure 3-10 shows how to code a while loop. This is one way that Java implements a control structure known as the iteration structure. This structure lets you repeat a block of statements. When a while loop is executed, Java executes the statements within the braces of the loop while the Boolean expression at the beginning of the statement is true. In other words, the loop ends when the expression becomes false. AS a result, if the expression is false when the statement starts, Java never executes any of the statements within the loop. In the first example, the Boolean expression for the while loop uses the equalslgnoreCase method to check whether the Suing variable named choice is equal to “y” or “Y”. Ifso, the statements within this loop do some processing. Then, the statements within the loop prompt the user to enter a “y" to continue or an “n” to exit. As a result, if the user enters “y” or “Y”, the loop executes again, Otherwise, the loop ends. The braces of the loop define a block of code. As a result, any variables that are defined within this block of code have block scope. In other words, these variables can’t be accessed outside the loop. That's why the String variable named choice is defined before the loop. That way, it can be accessed by the loop’s Boolean expression and by the statements coded within the loop. ‘The second example shows how to code a loop that prints the numbers 1 through 4 to the console. Here, a counter variable (or just counter) named i is initialized to 1 before the loop starts. Within the loop, the first statement prints the counter variable to the console. Then, the second statement adds I to the counter variable. When the value of the counter variable becomes 5, the Boolean expression for the while loop is no longer true. As a result, the loop ends. When coding loops, it’s common to use a counter variable, and it’s common to use a single letter like i as the name of a counter variable. If you don’t code a loop correctly, the loop might never end, For instance, it you forget to code the statement that adds 1 to the counter variable in the second example, the loop never ends because the counter never gets to 5. This is known as an infinite loop. Then, you have to cancel the application so you can debug your code. In Eclipse, you can do that by clicking on the Terminate button that’s available from the Console window when a console application is running. Chapter 3 How to use classes and methods 88 The syntax of the while loop A loop that continues while choice is “y” or “Y’ while (booleantxpression) ¢ statements d String choice = *y"; while (choice.equalstgnorecase("y")) ( // get input from the user, process it, and display output here 1/ see if the user wants to continue System.out.print ("Continue? (y/n): "); choice = s¢.nextLine()7 System.out -printin(); » A loop that prints 1 through 4 to the console int 4 = 1; while (i <5) ( System.out.printin("Loop * + i); aedea y The console it Description A while loop executes the block of state braces as long as the Boolean expression is true, When the expression becomes false, the while loop skips its block of statements so execution continues with the next statement in sequence. Any variables that are declared in the block of statements for a while loop have block scope. AS a result, you can only access them within that block. If the Boolean expression in a while loop never becomes false, the loop never ends. Then, the application goes into an infinite loop. In Eclipse, you can cancel an infinite loop by clicking on the Terminate button in the Console window. Figure 3-10 How to code a while loop 84 Section 1 Get started right How to code an if/else statement Figure 3-11 shows how to use the iffelse statement (or just if statement) to control the logic of your applications. This statement is the Java implementation of a control structure known as the selection structure because it lets you select different actions based on the results of a Boolean expression. The syntax summary shows that you can code an if statement with just an if clause, you can code it with one or more else if clauses, and you can code it with final else clause. Here, the ellipsis (...) means that the preceding element (in this case the else if clause) can be repeated as many times as it is needed. And. the brackets { ] mean that the element is optional. When an iffelse statement is executed, Java begins by evaluating the Boolean expression in the if clause. If it’s true, Java executes the statements within this clause and skips the rest ofthe if/else statement. If it’s false, Java evaluates the first else if clause (if there is one). Then, if its Boolean expression is true, Java executes the statements within this else if clause and skips the rest of the if/else statement. Otherwise, Java evaluates the next else if clause. This continues with any remaining else if clauses. Finally, if none of the clauses contains a Boolean expression that evaluates to true, Java executes the statements in the else clause (if there is one). However, if none of the Boolean. expressions are true and there is no else clause, Java doesn’t execute any statements. If you want to code two or more statements within a clause, you must use braces to identify the block of code for the clause as shown in the first three examples. Then, if you declare a variable within a block, that variable has block scope, which means that it can only be accessed within that block. That's why the price variable used in these examples is declared before the if statement. That way, it can be accessed by any clause in the if/else statement. If a clause only contains one statement, you aren't required to enclose that, statement in braces. However, t's generally considered a good practice to always use braces for the clauses of an iffelse statement for two reasons. First, the braces clearly identify the start and end of the clause. Second, the braces make it easy to add additional statements to the clause later. ‘The examples in this figure set the price variable depending on the value that’s stored in a String variable named productCode. For example, the third example sets the price to 57.50 if the productCode variable is equal to “java”. It sets the price to 57.50 if the productCode variable is equal to “jsp”. It sets the price to 54.50 if the productCode variable is equal to “mysql”. And it sets the price to 49.50 if the productCode variable isn’t equal to “java”, “jsp”, or “mysql”. Chapter 3 How to use classes and methods 85: The syntax of the if/else statement Af (booleanExpression) (statenents) ise if (booleantxpression) {statenents}] [else {statements} ) Examples of if/else statements Without an else if or else clause double price = 49.50; Af (productCode.equalstgnorecase("Java")) ¢ price = 57.50 y With an else clause double price; Af (productCode.equalstgnorecase("java")) ¢ price = 57.507 y else ¢ price = 49.507 y With two else if clauses and an else clause Af (productCode.equalstgnoreCase ("a1 price = 57.507 } else if (productCode. equalergnorecas price = 57.50; } ese 12 (productcode. equalergnorecas price = 54.50; } else ¢ price = 49.50; y Description © An ifelse statement, or just if statement, always contains an if clause. In addition, it can contain one or more else if clauses, and a final else clause. ‘© Any variables that are declared within a block for an iffelse clause have block scope. AS a result, they can only be accessed within that block. ‘© Ifa clause requires just one statement, you don’t have to enclose the statement in braces. However, it’s generally considered a good practice to always include braces. ‘That way, if you decide to add more statements to a clause later, you won't acciden- tally introduce a bug. Figure 3-11 How to code ielse statements, Section 1 Get started right The Line Item application To put the skills in this chapter into the context of an application, the next two figures present the Line Item application. If you understand the code presented in this chapter, you should be able to write comparable Java applica- tions of your own. The user interface Figure 3-12 shows the console for the Line Item application. This applica- tion starts by displaying a welcome message on the console. Then, it prompts the user to enter a product code and a quantity. Next, it displays the data for the line item. To get that data, the application retrieves the price based on the product code entered by the user, and it calculates the total by multiplying the price and quantity. After displaying the data for the line item, the application prompts the user to enter a “y” to continue or an “n” to exit. If the user enters a “y” or “Y", he or she can enter another line item. If the user enters “n” or any other character, the application ends and displays an exit message. Chapter 3 The console after two calculations Welcome to the Line Item Calculator Enter product code: java Enter quantity: 2 LINE ITEM code: java Price: $57.50 Quantity: 2 Total: $115.00 Continue? (y/n): y Enter product code: jsp Enter quantity: = 1 LINE ITEM Code: isp Price: $57.50 Quantity: = 2 Total: $57.50 Continue? (y/n): 2 By Description 87 How to use classes and methods When the application starts, the user can enter a product code that identifies a product and the quantity for that product. The application determines the product price based on the product code. Then, it calculates the total amount for the line item and displays the line item. After calculating the total for the invoice, the user can enter “y” or “Y” at the prompt to continue. Or, the user can enter “1 application, ‘The user terface for the Lineltem application igure 3-12 "or any other character to end the Section 1 Get started right The code Figure 3-13 shows the code for the Line Item application. Although this application is simple, it gets input from the user, performs a calculation that uses this input, and displays the result of the calculation. This code begins with a package statement that declares that it is stored in the murach.lineitem package. As a result, this code is stored in the ‘murach/lineitem subfolder of the application folder. The two import statements import the NumberFormat and Scanner classes. As a result, the rest of this code can use these classes without having to prefix the class name with the package name. The class declaration specifies a name of LineltemApp. As a result, this code is stored ina file named LineltemApp.java. The main method is coded within the braces of the LineltemApp class. This ‘method is executed when you run the LineltemApp class. ‘The main method begins by printing a welcome message to the console. Then, it creates a Scanner object named sc. Although this object could be created within the while loop, that would mean that the object would be recreated each time through the loop, which would be inefficient. Before the while loop, the code declares a String variable named choice and initializes it to “y”. Then, the loop checks whether the choice variable is equal to “y". If so, it starts by getting the product code from the user and storing it in a String variable named productCode. Then, it gets a quantity from the user, converts it from a String object to an int value, and stores it in a variable named quantity. After getting this data, an if/else statement sets the double variable named price based on the value of product code. If, for example, the productCode is equal to “java”, the price is set to 57.50. When the iffelse statement is finished, this code calculates the line item total by muluplying the price and quantity. Then, it stores the result of that calculation in a double variable named total. ‘After this calculation, this code uses the NumberFormat class to apply currency formatting to the price and total variables. In addition, it creates a String variable named message that contains string literals, variables, and escape sequences for new line characters. Then, it prints that string to the console, ‘After printing this data to the console, this code displays a message that asks the user if he or she wants to continue. If the user enters “y" or ““Y", the loop is, repeated. Otherwise, the application ends. If you're new to programming, you can learn a lot by writing simple applications like the Line Item application. This gives you a chance to become comfortable with getting input, performing calculations, and displaying output In addition, it gives you a chance to get comfortable with control statements such aas while loops and if/else statements. Chapter 3 How to use classes and methods 89 The code for the Lineltem application package murach. lineitem; import java.text .NumberFormat; import Java-util.scanner; public class LinertemApp ( public static void main(string args{]) ¢ ‘Syatem.out.printin("Welcome to the Line rtem Calculator"); System.out .printin(); Figure 3-13 Scanner sc = new Scanner(System.in); String choice = "y' while (choice.equalstgnorecase(*y")) ( > // get input from user System.out print ("Enter product code: * String productCode = sc.nextLine() System.out.print ("Enter quantity: "); int quantity = Integer.parseInt (sc.nextLine()); // set product price based on product code double price; if (productCode.equalsrgnorecase("Javé price = 57.5 ) elee if (productCode. equalergnorec: price = 57.50; if (productCode. equalstgnoreca: price = 54.50; ) else ( price = 0; ne ("3p") ) el (emysai")) ¢ // calculate total double total = price * quantity: 17 format and display output NumberFormat currency = NumberFormat .getCurrencyInstance(); String priceFormatted = currency. format (price); String totalFormatted = currency. format (total); String message = "\nLINE ITEM\n" + “Code: "+ productcode + "\n" + "price "+ pricerormatted + "\n" + wguantity: "+ quantity + "\n" + “Total: "+ totalrormatted + "\n"; System.out .printin(message); // see if the user wants to continue System.out.print ("Continue? (y/n): ")+ choice = sc-next (); System.out .printin(); sc-close(); System.out .printin(*Bye!"); ‘The code for the Lineltem application 90 Section 1 Get started right The Future Value application This chapter finishes by presenting another application, the Future Value application, This application is similar in some ways to the Line Item applica- tion, However, it uses a loop to calculate the future value of a monthily invest- ‘ment that’s made over a series of years. The user interface Figure 3-14 shows the console for this application, Here, the user starts by entering the monthly investment, the yearly interest rate, and the number of years for the investment, Then, the application calculates and displays the future ‘value, and it prompts the user to see if he or she wants to continue. At that point, the user can enter a “y” to continue or an “n” to exit Chapter 3 How to use classes and methods 94 The console after two calculations Welcome to the Future Value Calculator Enter monthly investment: 100 Enter yearly interest rate: 3 Enter number of year: 3 Future value: $3,772.46 continue? (v/a): ¥ Enter monthly investment: Enter yearly interest rate: Enter number of years: Future value: $4,525.79 Continue? (y/n): n By Description © When the application statts, user eal Wer a monthly investment, yearly interest rate, and number of years. Then, it calculates the future value of the investment at the end of the specified number of years and displays that value to the user. © Affer calculating the future value, the user can enter “y” or “Y" at the prompt to continue, Or, the user can enter “n” or any other character to end the application. Figure 3-14 The user interface for the Future Value application 92 Section |Get started right The code Figure 3-15 shows the code for this application. This code uses a while loop to determine when the application ends. Within this loop, the code gets the three entries from the user. Then, it converts these entries to the same time unit, which is months. To do that, it multiplies the number of years by 12 and divides the yearly interest rate by 12. In addition, it divides the yearly interest rate by 100 so it calculates the interest correctly. Once those variables are prepared, a second while loop calculates the future value. This loop executes one time for each month, Within this loop, the first statement adds the monthly investment to the future value, The second statement calculates the amount of monthly interest. The third statement adds the monthly interest to the future value. And the fourth statement increments the counter variable. When this loop finishes, the code displays the result. To do that, it uses the NumberFormat class to apply currency formatting to the future value. Then, it asks whether the user wants to continue. Chapter 3 How to use classes and methods 98. The code for the Future Value application package murach.fv; import java.text .NumberFormat; import Java-util.scanner; public class Main ( public static void main(string{] args) ( Figure 3-15 77 aisplay 2 welcome message System.out .printin(*Welcome to the Future Value Calculator"); System.out .printin(); Scanner sc = new Scanner(System.in); String choice = "y"; while (choice.equalstgnoreCase(*y")) ( // get input from user System.out print ("Enter monthly investment"); double monthlyInvestment = Double.parseDouble(sc.nextLine()); System.out print ("Enter yearly interest rate: "); double yearlyInterestRate = Double.parseDouble(sc.nextLine()) 7 System.out print ("Enter number of years: ” int years = Integer.parseInt (sc.nextLine() J) convert yearly values to monthly values double monthlyInterestRate = yearlyInterestRate / 12 / 100; int months = years * 1 // calculate the future value double futurevalue = 0; int i= 1; while (i <= months) ( futurevalue = futurevalue + monthlyInvestment double monthivinterestAmount = futureValue * monthlyrnterestRate; futureValue = futureValue + monthlyInterestAmount; ieieay y // format and display the result System.out .printin("Future valu ne NumberFormat .getCurrencyInstance() . format (futureValue) System.out .printin(); // see if the user wants to continue System.out print ("Continue? (y/n): " choice = sc.nextLine(); System-out.printin(); System.out .printin(*Bye!"); ‘The code for the Future Value application 94 Section 1 Get started right Perspective The goal of this chapter has been to show you how to create a console application that uses classes and methods from the Java API to get input from the user and display output to the user. Now, if you understand how the Line Item and Future Value applications work, you've come a long way. However, these applications don’t use objects in a professional way. That's why the next two chapters show you how to convert the Line Item application into an object-oriented application that uses objects in a professional way. Also, keep in mind that this chapter is just an introduction to Java program- ming. As a result, you'll learn more details about writing Java code as you progress through this book. For example, you'll lear more about coding control statements in chapter 8 Summary © You call a method from an object and you call a static method from a class. A method may require one or more arguments. ‘© Before you use a class from the Java SE API that isn’t in the java.lang package, you typically code an import statement for the class. ‘© When you use a constructor to create an object from a Java class, you are creating an instance of the class. You can use the static methods of the Integer and Double classes to convert strings to int and double values. ‘© You can use the NumberFormat class to apply standard currency, percent, and number formats to any of the primitive numeric types. © You can code a while loop that executes a block of statements repeatedly when its Boolean expression returns a true value and skips that block of statements when its Boolean expression returns a false value. ‘© You can code an if statement to control the logic of an application based on the true or false values of Boolean expressions. Chapter 3 How to use classes and methods 95: Exercise 3-1 Modify the Line Item application In this exercise, you can test and modify the Line Item application presented at the end of this chapter. ‘Test the application Start the Eclipse IDE and import the project named ch03_ex1_Lineltem. This project should be in this folder: Cr \murach\Java_eclipse\ex arts 2. Open the file named LineltemApp java. Then, review the code for this file, 3. ication and test it with valid product codes like “java” and valid quantities like 2, 10, and 1000 that make it easy to see whether or not the calculations are correct. 4, Run the application again and test it with an invalid quantity value like “two”, This should cause the application to crash, Study the crror message and determine which line of source code was running when the error occurred. 5. Run the application again and enter “x” when the application asks you whether you want fo continue. What happens and why? Modify the application 6. Modify the iffelse statement so it sets a description for the product. Then, modify the code that displays the data for the line item so it includes the description, When you're done, the application should look like this: Welcome to the Line item Calculator Enter product code: java Enter quantity: 2 Description: Murach's Java Programming Price: $57.50 Quantity: 2 Totals $115.00 continue? (y/n)+ Modity the iffelse statement so it includes another product code named “android”, Make up a description and price that correspond with this code. Modify the code that displays the data for the line item so that it doesn’t declare the priceFormatted and totalFormatted variables. To do that, replace these variables with a call to the format method of the NumberFormat object named currency. This should cut two lines of code.

You might also like