Download presentation
Presentation is loading. Please wait.
Published byDarcy Walters Modified over 9 years ago
1
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming
2
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 2 XXX Numeric Type Conversion XXX Consider the following statements: byte i = 100; long k = i * 3 + 4; double d = i * 3.1 + k / 2;
3
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 3 XXX Conversion Rules XXX When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1. If one of the operands is double, the other is converted into double. 2. Otherwise, if one of the operands is float, the other is converted into float. 3. Otherwise, if one of the operands is long, the other is converted into long. 4. Otherwise, both operands are converted into int.
4
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 4 Type Casting Implicit casting double d = 3; (type widening) Explicit casting int i = (int)3.0; (type narrowing) int i = (int)3.9; (Fraction part is truncated) What is wrong here?int x = 5 / 2.0;
5
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 5 import java.util.Scanner; public class SalesTax { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter purchase amount: "); double purchaseAmount = input.nextDouble(); double tax = purchaseAmount * 0.06; System.out.println("Sales tax is " + (int)(tax * 100) / 100.0); } Problem: Keeping Two Digits After Decimal Points Write a program that displays the sales tax with two digits after the decimal point. FYI: This does NOT work as advertised!
6
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 6 XXX Casting in an Augmented Expression XXX In Java, an augmented expression of the form x1 op= x2 is implemented as x1 = (T)(x1 op x2), where T is the type for x1. Therefore, the following code is correct. int sum = 0; sum += 4.5; // sum becomes 4 after this statement sum += 4.5 is equivalent to sum = (int)(sum + 4.5).
7
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 7 Problem: Computing Loan Payments This program lets the user enter the interest rate, number of years, and loan amount, and computes monthly payment and total payment.
8
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 8 import java.util.Scanner; public class ComputeLoan { public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Enter yearly interest rate System.out.print("Enter yearly interest rate, for example 8.25: "); double annualInterestRate = input.nextDouble(); // Obtain monthly interest rate double monthlyInterestRate = annualInterestRate / 1200; // Enter number of years System.out.print( "Enter number of years as an integer, for example 5: "); int numberOfYears = input.nextInt(); // Enter loan amount System.out.print("Enter loan amount, for example 120000.95: "); double loanAmount = input.nextDouble(); // Calculate payment double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)); double totalPayment = monthlyPayment * numberOfYears * 12; // Display results System.out.println("The monthly payment is $" + (int)(monthlyPayment * 100) / 100.0); System.out.println("The total payment is $" + (int)(totalPayment * 100) / 100.0); }
9
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 9 Character Data Type char letter = 'A'; (ASCII) char numChar = '4'; (ASCII) char letter = '\u0041'; (Unicode) char numChar = '\u0034'; (Unicode) Four hexadecimal digits.
10
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 10 Unicode Format Java characters use Unicode, a 16-bit encoding scheme established by the Unicode Consortium to support the interchange, processing, and display of written texts in the world’s diverse languages. Unicode takes two bytes, preceded by \u, expressed in four hexadecimal numbers that run from '\u0000' to '\uFFFF'. So, Unicode can represent 65535 + 1 characters. Unicode \u03b1 \u03b2 \u03b3 for three Greek letters
11
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 11 Problem: Displaying Unicodes Write a program that displays two Chinese characters and three Greek letters.
12
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 12 import javax.swing.JOptionPane; public class DisplayUnicode { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "\u6B22\u8FCE \u03b1 \u03b2 \u03b3", "\u6B22\u8FCE Welcome", JOptionPane.INFORMATION_MESSAGE); }
13
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 13 Escape Sequences for Special Characters Description Escape Sequence Unicode Backspace \b\u0008 Tab \t\u0009 Linefeed \n\u000A Carriage return \r\u000D Backslash \\\u005C Single Quote \ ' \u0027 Double Quote \ " \u0022
14
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 14 Appendix B: ASCII Character Set ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
15
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 15 ASCII Character Set, cont. ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
16
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 16 Casting between char and Numeric Types int i = ' a ' ; // Same as int i = (int) ' a ' ; char c = 97; // Same as char c = (char)97;
17
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 17 Problem: Monetary Units This program lets the user enter the amount in decimal representing dollars and cents and output a report listing the monetary equivalent in single dollars, quarters, dimes, nickels, and pennies. Your program should report maximum number of dollars, then the maximum number of quarters, and so on, in this order.
18
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 18 import java.util.Scanner; public class ComputeChange { public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Receive the amount System.out.print( "Enter an amount in double, for example 11.56: "); double amount = input.nextDouble(); int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; // Display results System.out.println("Your amount " + amount + " consists of \n" + "\t" + numberOfOneDollars + " dollars\n" + "\t" + numberOfQuarters + " quarters\n" + "\t" + numberOfDimes + " dimes\n" + "\t" + numberOfNickels + " nickels\n" + "\t" + numberOfPennies + " pennies"); }
19
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 19 Trace ComputeChange int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; 1156 remainingAmount remainingAmount initialized Suppose amount is 11.56
20
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 20 Trace ComputeChange int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; 1156 remainingAmount Suppose amount is 11.56 11 numberOfOneDollars numberOfOneDollars assigned animation
21
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 21 Trace ComputeChange int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; 56 remainingAmount Suppose amount is 11.56 11 numberOfOneDollars remainingAmount updated animation
22
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 22 Trace ComputeChange int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; 56 remainingAmount Suppose amount is 11.56 11 numberOfOneDollars 2 numberOfOneQuarters numberOfOneQuarters assigned animation
23
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 23 Trace ComputeChange int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; 6 remainingAmount Suppose amount is 11.56 11 numberOfOneDollars 2 numberOfQuarters remainingAmount updated animation
24
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 24 The String Type The char type only represents one character. To represent a string of characters, use the data type called String. For example, String message = "Welcome to Java"; String is actually a predefined class in the Java library just like the System class and JOptionPane class.
25
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 25 String Concatenation // Three strings are concatenated String message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2 String s = "Chapter" + 2; // s becomes Chapter2 // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s1 becomes SupplementB
26
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 26 Debugging Logic errors are called bugs. The process of finding and correcting errors is called debugging. A common approach to debugging is to use a combination of methods to narrow down to the part of the program where the bug is located. You can hand-trace the program (i.e., catch errors by reading the program), or you can insert print statements in order to show the values of the variables or the execution flow of the program. This approach might work for a short, simple program. But for a large, complex program, the most effective approach for debugging is to use a debugger utility.
27
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 27 Debugger Debugger is a program that facilitates debugging. You can use a debugger to F Execute a single statement at a time. F Trace into or stepping over a method. F Set breakpoints. F Display variables. F Display call stack. F Modify variables.
28
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 28 JOptionPane Input This book provides two ways of obtaining input. 1. Using the Scanner class (console input) 2. Using JOptionPane input dialogs
29
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 29 Getting Input from Input Dialog Boxes String input = JOptionPane.showInputDialog( "Enter an input");
30
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 30 Getting Input from Input Dialog Boxes String string = JOptionPane.showInputDialog( null, “Prompting Message”, “Dialog Title”, JOptionPane.QUESTION_MESSAGE);
31
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 31 Many Ways to Invoke the Method There are several ways to use the showInputDialog method. For the time being, you only need to know two ways to invoke it. One is to use a statement as shown in the example: String string = JOptionPane.showInputDialog(null, x, y, JOptionPane.QUESTION_MESSAGE); where x is a string for the prompting message, and y is a string for the title of the input dialog box. The other is to use a statement like this: JOptionPane.showInputDialog(x); where x is a string for the prompting message.
32
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 32 XXX Converting Strings to Integers XXX The input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns “123”. To obtain the input as a number, you have to convert a string into a number. To convert a string into an int value, you can use the static parseInt method in the Integer class as follows: int intValue = Integer.parseInt(intString); where intString is a numeric string such as “123”.
33
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 33 XXX Converting Strings to Doubles XXX To convert a string into a double value, you can use the static parseDouble method in the Double class as follows: double doubleValue =Double.parseDouble(doubleString); where doubleString is a numeric string such as “123.45”.
34
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 34 Problem: Computing Loan Payments Using Input Dialogs ComputeLoanUsingInputDialog Run Same as the preceding program for computing loan payments, except that the input is entered from the input dialogs and the output is displayed in an output dialog.
35
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 35 import javax.swing.JOptionPane; public class ComputeLoanUsingInputDialog { public static void main(String[] args) { // Enter yearly interest rate String annualInterestRateString = JOptionPane.showInputDialog( "Enter annual interest rate, e.g., 8.25:"); // Convert string to double double annualInterestRate = Double.parseDouble(annualInterestRateString); // Obtain monthly interest rate double monthlyInterestRate = annualInterestRate / 1200; // Enter number of years String numberOfYearsString = JOptionPane.showInputDialog( "Enter number of years as an integer, \ne.g., 5:"); // Convert string to int int numberOfYears = Integer.parseInt(numberOfYearsString); // Enter loan amount String loanString = JOptionPane.showInputDialog( "Enter loan amount, e.g., 120000.95:"); // Convert string to double double loanAmount = Double.parseDouble(loanString); // Calculate payment double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)); double totalPayment = monthlyPayment * numberOfYears * 12; // Format to keep two digits after the decimal point monthlyPayment = (int)(monthlyPayment * 100) / 100.0; totalPayment = (int)(totalPayment * 100) / 100.0; // Display results String output = "The monthly payment is $" + monthlyPayment + "\nThe total payment is $" + totalPayment; JOptionPane.showMessageDialog(null, output); }
36
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 36
37
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 37
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.