Chapter3-Numerical Data and Expression (Part 2)
Chapter3-Numerical Data and Expression (Part 2)
STIA1113 : Programming I
NUMERICAL COMPUTATION &
EXPRESSION (part 2)
• This topic focuses on:
– data conversions
– complex arithmetic computation
– accepting input from the user
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
Data Conversion
• Widening conversions are safest because they tend to
go from a small data type to a larger one (such as a
short to an int)
• 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)
• In Java, data conversions can occur in three ways:
– assignment conversion
– promotion
– casting
Data Conversion
can be represented as
(-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a)
Mathematical Methods in Java
Math.sqrt(x) square root
Math.pow(x, y) power xy
Math.exp(x) ex
Analyzing an Expression
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
Reading Input
• 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
• 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
• The details of object creation and class libraries are
discussed further in Chapter 3
//********************************************************************
// 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;
message = scan.nextLine();
import java.util.Scanner;
message = scan.nextLine();
import java.util.Scanner;
1. Write a Java program that takes two numbers as input and display
the product of two numbers.
Test Data:
Input first number: 25
Input second number: 5
2. Write a Java program that reads an integer between 0 and 1000 and
adds all the digits in the integer.
Test Data
Input an integer between 0 and 1000: 565
Expected Output :
The sum of all digits in 565 is 16