Topic 3
NUMERICAL
COMPUTATIO
N&
EXPRESSION
(PART 2)
1
1. To learn about
data conversions
2. To learn complex
OBJECTIV arithmetic
ES computation
3. To learn about
accepting input
from the user
2
OUTLINE
Data Conversion
Complex arithmetic computation
Interactive Programs
3
DATA CONVERSION
Sometimes it is convenient to convert data
from one type to another.
For example, in a particular situation we may
want to treat an integer as a floating point
value.
These conversions do not change the type of a
variable or the value that's stored in it – they
only convert a value as part of a computation.
4
DATA CONVERSION
Two types of data conversion:
1. Widening conversions are the safest
because they tend to go from a small data
type to a larger one (such as a short to an
int)
2. Narrowing conversions can lose information
because they tend to go from a large data
type to a smaller one (such as an int to a
short)
5
DATA CONVERSION
Widening Conversions Narrowing Conversions
6
DATA CONVERSION
In Java, data conversions can occur in
three ways:
Assignment conversion
Promotion
Casting
7
Assignment conversion
occurs when a value of one
type is assigned to a
ASSIGN variable of another.
MENT
Example:
int dollars = 20;
CONVER double money = dollars;
Only widening conversions
SION can happen via assignment.
Note that the value or type
of dollars did not change.
8
Promotion happens
automatically when operators in
expressions convert their
operands.
Examples:
PROMO int count = 12;
double sum = 490.27;
TION
result = sum /
count;
The value of count is converted
to a floating-point value to
perform the division calculation.
9
Casting is the most powerful, and
dangerous, technique for
conversion.
Both widening and narrowing
conversions can be accomplished
by explicitly casting a value.
CASTIN To cast, the type is put in
parentheses in front of the value
G being converted.
int total = 50;
float result = (float)total/6;
Without the cast, the fractional
part of the answer would be lost.
10
OUTLINE
Data Conversion
Complex arithmetic computation
Interactive Programs
11
THE math CLASS
Math class: contains methods like sqrt
and pow
To compute xn, you write Math.pow(x,
n)
However, to compute x2 it is significantly
more efficient simply to compute x * x
To take the square root of a number, use
the Math.sqrt; for example,
Math.sqrt(x)
12
THE math CLASS
In Java,
can be represented as
(-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a)
13
MATHEMATICAL METHODS
IN JAVA
Math.sqrt(x) square root
Math.pow(x, y) power xy
Math.exp(x) ex
Math.log(x) natural log
Math.sin(x), Math.cos(x), sine, cosine, tangent (x
Math.tan(x) in radian)
Math.round(x) closest integer to x
Math.min(x, y), Math.max(x, y) minimum, maximum
14
ANALYZING AN
EXPRESSION
15
OUTLINE
Data Conversion
Complex arithmetic computation
Interactive Programs
16
INTERACTIVE PROGRAM
CUST A
RM 10.50 +
RM 12.00 =
RM22.50
CUST B
RM 10.00 +
RM 12.00 +
RM 30.00 =
RM 52.00
17
DEMO
INTERACTIVE
PROGRAM IN
JGRASP
18
CLASSES IN JAVA
String
Tokenizer
Scanner Class
…
Import Class Class
_______
_______ _______
_______ _______
CalculateRect
JAVA.util class library
Class
_______ CalculatePric
_______ e Class
_______
_______
Classes created by JAVA users
19
HOW TO CREATE
INTERACTIVE PROGRAMS?
1. Import Scanner class:
import java.util.Scanner;
2. Create Scanner object:
Scanner scan = new Scanner (System.in);
Scanner read = new Scanner (System.in);
3. Once created, the Scanner object can be used to
invoke various input methods, such as:
answer = scan. nextLine();
answer = read.nextLine();
20
INTERACTIVE PROGRAMS
Programs generally need input on which to
operate.
The Scanner class provides convenient
methods for reading input values of various
types.
A Scanner object can be set up to read input
from various sources, including the user typing
values on the keyboard.
Keyboard input is represented by the
System.in object.
21
The following line creates a Scanner object
that reads from the keyboard:
Scanner scan = new Scanner (System.in);
The new operator creates the Scanner object
Once created, the Scanner object can be used
to invoke various input methods, such as:
answer = scan.nextLine();
READING INPUT
22
The Scanner class is part of the
java.util class library, and must be
imported into a program to be used
The nextLine method reads all of the
input until the end of the line is found
See Echo.java
READING INPUT
23
METHODS FOR
SCANNER
Methods Descriptions
nextByte() Reads an integer of the byte type
nextShort() Reads an integer of the short type
nextInt() Reads an integer of the integer type
nextLong() Reads an integer of the long type
nextFloat() Reads a number of the float type
nextDouble() Reads a number of the double type
next() Reads a string that ends before whitespace
character
nextLine() Reads a line of text
24
DESIGN OF INTERACTIVE PROGRAM:
PSEUDOCODE & FLOW CHART
Start
Start
Input message
Input message
Print "You entered: \"" + message +
"\“” Print "You entered: \""
+ message + "\""
End
End
25
//********************************************************************
// Echo.java Author: Lewis/Loftus
//
// Demonstrates the use of the nextLine method of the Scanner class
// to read a string from the user.
//********************************************************************
import java.util.Scanner;
public class Echo
{
//-----------------------------------------------------------------
// Reads a character string from the user and prints it.
//-----------------------------------------------------------------
public static void main (String[] args)
{
String message;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter a line of text:");
message = scan.nextLine();
System.out.println ("You entered: \"" + message + "\"");
}
}
26
Sample Run
Enter a line of text:
I am enjoying myself with JAVA
You entered: "I am enjoying myself with JAVA"
27
DESIGN OF INTERACTIVE
PROGRAM: PSEUDOCODE &
FLOW CHART
Start
Start
Input miles,
Input miles, gallons gallons
Calculate mpg = miles / gallons
Print “Miles per gallon” +mpg
mpg = miles / gallons
End
Print “Miles per gallon”
+mpg
End
28
//********************************************************************
// GasMileage.java Author: Lewis/Loftus
//
// Demonstrates the use of the Scanner class to read numeric data.
//********************************************************************
import java.util.Scanner;
public class GasMileage
{
//-----------------------------------------------------------------
// Calculates fuel efficiency based on values entered by the
// user.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int miles;
double gallons, mpg;
Scanner scan = new Scanner (System.in);
continue
29
continue
System.out.print ("Enter the number of miles: ");
miles = scan.nextInt();
System.out.print ("Enter the gallons of fuel used: ");
gallons = scan.nextDouble();
mpg = miles / gallons;
System.out.println ("Miles Per Gallon: " + mpg);
}
}
Sample Run
Enter the number of miles: 328
Enter the gallons of fuel used: 11.2
Miles Per Gallon: 29.28571428571429
30
TODAY’S TAKE
AWAY
Data conversions
- Widening & narrowing
conversions
- Assignment, promotion, casting
Complex arithmetic computation
- Math class
Accepting input from the user
- Importing Scanner class
- Creating Scanner object
- Reading input from keyboard
using Scanner methods,
e.g.: nextInt(), nextLine().
31