Download II. Types of primitive data values

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

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

Document related concepts
no text concepts found
Transcript
Chapter 3. Numerical Data
Reference: Chapter 3, and powerpoint presentation from publisher.
Objectives of this chapter:
- Understand the type of numerical data
- Difference between primitive data (variable) and object
- Understand arithmetic expressions (operations due to different types)
- Get to know math class, GregorianCalendar class, DecimalFormat class,
input and output with System.in and System.out
I. Introduction
Major challenge: “=” is actually assignment rather than equality.
II. Types of primitive data values
II.1. Variable has three properties:
- A memory location to store the value
- The type of data stored in the memory location, and
- The name used to refer to the memory location
Six numerical data types: byte, short, int, long, float, and double.
II.2. Constant: If we want the value to remain the same, we use a constant.
final double PI
= 3.14159
final int
MONTH_IN_YEAR = 12;
The constant PI is called a named constant or symbolic constant. The
second type of constant is called a literal constant – the actual value.
What is the type of literal constant 345.79? It is double. So, the following
will create compilation error:
float number;
number = 345.79;
This is because the variable (float) has lower precision than that of the constant
(double). To correct this error, we have to write the assignment statement as:
number = (float) 345.79; or number = 345.79f;
final double SPEED_OF_LIGHT = 3.0E+10D
(literal constant suffixed by f, F, d or D).
CS1101Z
1 of 5
II.3. Primitive vs Reference
Numerical data are called primitive data types
Objects are called reference data types, because the contents are addresses
that refer to memory locations where the objects are actually store.
III. Arithmetic Expressions
Assignment statement, precedence rules, (implicit and explicit) type casting.
To input a numerical value, we have to first input a String object and then convert
it to a numerical representation. We call such operation a type conversion.
To perform the necessary type conversion in Java, we use different utility classes
called wrapper classes. The name wrapper derives from the fact that these
classes surround, or wrap, primitive data with useful methods.
int num = Integer.parseInt(“14”);
String str = JOptionPane.showInputDialog(null, “Enter age:”);
int age = Integer.parseInt(str);
String radiusStr = JOptionPane.showInputDialog(null, “Enter radius:”);
Double radius = Double.parseDouble(radiusStr);
IV. Useful Classes
Useful classes:
System.out
System.in ( need to use together with IOException, so import
java.io.IOException; or, use it together with Scannar)
Scanner (import java.util.*)
DecimalFormat (import java.text.*)
Math class
GregorianCalender (import java.util.*)
See/Demo of examples come with your textbook:
- Ch3Circle.java (page 99) ….use Wrapper classes (Integer.parseInt(str))
- Ch3Circle3.java (page 105) ….use DecimalFormat
- Ch3Circle4.java (page 112) ….use Scanner
- Ch3PoleHeight (page 116) ….use Math class
- Ch3SelectWinner (page 118) ….use Math.random()
- Ch3TestCalendar (page 121) ….use GregorianCalendar()
CS1101Z
2 of 5
IV.1. System.out, System.in and Scanner
System.out refers to a precreated PrintStream object we use to output muyltiple
lines of text to the standard output window. The actual appearance of the
standard output window depends on which Java tool we use.
e.g. System.out.print(“x + x =” + ans);
System.out.println(“”);
System.out.println( “x + x =” + ans);
Analogous to System.out for output, we have System.in for input. We call the
technique to input data using System.in standard input. We also use the term
console input to refer to standard input.
Using System.in for input is slightly more complicated than using System.out for
output. System.in is an instance of the InputStream class that provides only a
facility to input 1 byte at a time with its read method. However, multiple bytes are
required to represent a primitive data type or a string (for example, 4 bytes is
used to store an int value). So to input primitive data values or strings easily, we
need an input facility to process multiple bytes as a single unit.
Try out the following program in DrJava to see:
class UseSystemIn {
public static void main ( String[] args ) {
int i = System.in.read();
System.Out.println(i);
}
}
and also try out:
import java.io.IOException;
class UseSystemIn2 {
public static void main (String[ ] args) {
try {
int i = system.in.read();
System.out.println(i);
}
catch (IOException e) {
System.out.println(“Unable to read from System.in”);
}
}
}
The most common way of using System.in for input is to associate a Scanner
object to the System.in object. A Scanner object will allow us to read primitive
data type values and strings. First we create a new Scanner object by passing
System.in as an argument:
CS1101Z
3 of 5
Import java.util.*;
Scanner scanner;
scanner = new Scanner (System.in);
Once we have a Scanner object, then we can call its nextInt method to input an
int.
int age;
Age = scanner.nextInt();
Or other types of numeric data, such as:
Double dNum1;
dNum1 = scanner.nextDouble();
Note that reading a string input is slightly more complicated than reading
numerical data. Compare the following:
System.out.print (“Enter your name: “);
name = scanner.next();
The above does not get all the words in a name. To remedy the problem,
Scanner scanner = new Scanner (System.in);
String lineSeparator = System.getProperty(“line.separator”);
Scanner.useDelimiter(lineSeparator);
System.out.print(“Enter your name: “);
String name = scanner.next();
IV.2. DecimalFormat
Import java.text.*;
DecimalFormat df = DecimalFormat(“0.000”);
Double radius = 0.123456;
System.out.println(“Radius : “ + df.format(radius)) ;
IV.3. Math Class
doube alpha = 10.0;
// angle
doube alphaRad = Math.toRadians(alpha);
double height = Math.sqrt(Math.sin(alphaRad));
// select the winner
int min = startingNumber + 1;
int max = startingNumber + count;
winningNumber = (int)(Math.floor(math.random() * (max – min +1)) + min);
System.out.println(“The Winning Number is “ + winningNumber);
CS1101Z
4 of 5
IV.3. GregorianCalendar Class
Import java.util.*;
e.g.
GregorianCalendar cal = new GregorianCalendar();
System.out.println(cal.getTime());
System.out.println(“ “);
System.out.println(“Year:
“ + cal.get(Calendar.YEAR));
System.out.println(“MONTH:
“ + cal.get(Calendar.MONTH));
System.out.println(“DATE:
“ + cal.get(Calendar.DATE));
System.out.println(“MINUTE:
“ + cal.get(Calendar.MINUTE));
e.g.
GregorianCalendar independenceDay = new GregorianCalendar(1965,
Calendar.AUGUST, 9);
SimpleDateFormat sdf = new SimpleDateFormat(“EEEE”);
JOptionPane.showMessageDialog(null, “Our independence day was on “
+ sdf.format(independenceDay.getTime()));
V. Sample Development
Problem statement: Write a loan calculator program that computes both
monthly and total payments for a given loan amount, annual interest rate, and
loan period.
Objects consideration – design – code – test
Objects consideration: JOptionPane, System.out, Math classes.
One way of design: input, process, output.
L R
Monthly payment =
N
 1 
1 

 1 R 
where L is the loan amount, R is the monthly interest rate, and N is the
number of payments. The monthly rate R is expressed in a fractional value, for
example, 0.01 for 1 percent monthly rate.
We do incremental coding for input, output, and then process. In this approach,
we test besides coding as we go along. Also, at the end of this, we may need to
do a more comprehensive understanding of monthly payment, total
payment….(number of significant digits etc.)
CS1101Z
5 of 5