Download int

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter 2 Elementary Programming
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
1
XXX Numeric Type Conversion XXX
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
2
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.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
3
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;
range increases
byte, short, int, long, float, double
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
4
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!
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);
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
5
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).
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
6
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.
loanAmount  monthlyInterestRate
monthlyPayment 
1
1
(1  monthlyInterestRate) numberOfYears12
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
7
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);
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
8
Character Data Type
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
Four hexadecimal digits.
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
9
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
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
10
Problem: Displaying Unicodes
Write a program that displays two Chinese
characters and three Greek letters.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
11
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);
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
12
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
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
13
Appendix B: ASCII Character Set
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
14
ASCII Character Set, cont.
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
15
Casting between char and
Numeric Types
int i = 'a'; // Same as int i = (int)'a';
char c = 97; // Same as char c = (char)97;
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
16
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.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
17
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
// Find the number of nickels in the remaining
System.out.print(
amount
"Enter an amount in double, for example 11.56: ");
int numberOfNickels = remainingAmount / 5;
double amount = input.nextDouble();
remainingAmount = remainingAmount % 5;
int remainingAmount = (int)(amount * 100);
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
// Find the number of pennies in the remaining
amount
int numberOfPennies = remainingAmount;
// Display results
System.out.println("Your amount " + amount + "
// Find the number of quarters in the remaining amount
consists of \n" +
int numberOfQuarters = remainingAmount / 25;
"\t" + numberOfOneDollars + " dollars\n" +
remainingAmount = remainingAmount % 25;
"\t" + numberOfQuarters + " quarters\n" +
"\t" + numberOfDimes + " dimes\n" +
// Find the number of dimes in the remaining amount
"\t" + numberOfNickels + " nickels\n" +
int numberOfDimes = remainingAmount / 10;
"\t" + numberOfPennies + " pennies");
remainingAmount = remainingAmount % 10;
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
18
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100);
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
remainingAmount
1156
remainingAmount
initialized
// 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;
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
19
animation
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100);
remainingAmount
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
numberOfOneDollars
// Find the number of quarters in the remaining amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
1156
11
numberOfOneDollars
assigned
// 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;
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
20
animation
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100);
remainingAmount
56
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
numberOfOneDollars
11
// Find the number of quarters in the remaining amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
remainingAmount
updated
// 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;
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
21
animation
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100);
remainingAmount
56
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
numberOfOneDollars
11
// Find the number of quarters in the remaining amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
numberOfOneQuarters
2
// Find the number of dimes in the remaining amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
numberOfOneQuarters
assigned
// 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;
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
22
animation
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100);
remainingAmount
6
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
numberOfOneDollars
11
// Find the number of quarters in the remaining amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
numberOfQuarters
2
// Find the number of dimes in the remaining amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
remainingAmount
updated
// 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;
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
23
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.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
24
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
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
25
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.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
26
Debugger
Debugger is a program that facilitates debugging.
You can use a debugger to
Execute
a single statement at a time.
Trace into or stepping over a method.
Set breakpoints.
Display variables.
Display call stack.
Modify variables.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
27
JOptionPane Input
This book provides two ways of obtaining input.
1.
2.
Using the Scanner class (console input)
Using JOptionPane input dialogs
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
28
Getting Input from Input Dialog Boxes
String input = JOptionPane.showInputDialog(
"Enter an input");
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
29
Getting Input from Input Dialog Boxes
String string = JOptionPane.showInputDialog(
null, “Prompting Message”, “Dialog Title”,
JOptionPane.QUESTION_MESSAGE);
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
30
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.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
31
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”.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
32
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”.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
33
Problem: Computing Loan Payments
Using Input Dialogs
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.
loanAmount  monthlyInterestRate
1
1
numberOfYears12
(1  monthlyInterestRate)
ComputeLoanUsingInputDialog
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Run
34
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 loan amount
String loanString = JOptionPane.showInputDialog(
"Enter loan amount, e.g., 120000.95:");
// Enter number of years
String numberOfYearsString = JOptionPane.showInputDialog(
"Enter number of years as an integer, \ne.g., 5:");
// 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;
// Convert string to int
int numberOfYears = Integer.parseInt(numberOfYearsString);
// 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);
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
35
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
36
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
37