Lecture 3 Program Elements
Download
Report
Transcript Lecture 3 Program Elements
Lecture 3
Program Elements
Instructors:
Fu-Chiung Cheng
(鄭福炯)
Associate Professor
Computer Science & Engineering
Tatung Institute of Technology
1
Outline
• Data types
• Variable declaration and use
• Decisions and loops
• Input and output
2
Primitive Data Types
• A data type: define values and the operators
• Each value stored in memory is associated with a
particular data type
• primitive data types: predefined data types in Java
Ex: A: integers: byte, short, int, long.
B: float, double.
C: boolean (true or false) (on or off)
D: char (unicode 16 bits for international languages)
3
Storage in Programming
Languages
• Registers
• Stack (handles & primitives in Java)
• Heap (all class objects in Java)
• Static storage
• Constant storage
• Non-RAM storage (persistent)
4
Primitive Data Types
• Integers:
Type
Storage
Min Value
Max Value
byte
short
int
long
8 bits
16 bits
32 bits
64 bits
-128
-32,768
-2,147,483,648
< -9 x 1018
127
32,767
2,147,483,647
> 9 x 1018
Note that Built-in types (primitives) are not object handles
handles: call by reference
5
primitives: call by value
Primitive Data Types
• Floating point:
Type
Storage
Approximate
Min Value
float
double
32 bits
64 bits
-3.4 x 1038
-1.7 x 10308
S
Exponent
Approximate
Max Value
3.4 x 1038
1.7 x 10308
Mantisa
6
Primitive Data Types
• char: Unicode character set
• A character set is an ordered list of characters
• The Unicode character set uses sixteen bits per character,
allowing for 65,536 unique characters
• International character set.
7
Primitive Data Types
•boolean: a true or false condition (two states: on or off)
• The reserved words true and false are the
only valid values for a boolean type
8
Primitive Data Types
•Same operations as C/C++
• Size of each data type is machine independent
9
Wrappers for primitive Data
Types
• For each primitive data type there is a corresponding
wrapper class.
Primitive Type
int
double
char
boolean
Wrapper Class
Integer
Double
Character
Boolean
• Wrapper classes are useful in situations where you need
an object instead of a primitive type
10
• They also contain some useful methods
Variables
• A variable is an identifier that represents a location in
memory that holds a particular type of data
• Variables must be declared before they can be used
• Syntax of a variable declaration:
data-type variable-name;
For example:
int total; // 4-byte int in stack
int total, count, sum;
int total = 0, count = 20;
float unitPrice = 57.25;
11
Scope of Variables
• Block statements:
group of statements delimited by braces
{ // begin of scope 1
int x=1;
System.out.println("x="+x);
{ // begin of scope 2
// int x=3; // can not redine x
int y=2;
System.out.println("x="+x);
System.out.println(“y=”+y);
}
}
12
Assignment Statements
• An assignment statement takes the following form:
variable-name = expression;
• The expression is evaluated and the result is stored in
the variable, overwriting the value currently stored
in the variable
• The expression can be a single value or a more
complicated calculation
13
Constants
• A constant is similar to a variable except that they keep
the same value throughout their existence
• They are specified using the reserved word final
in the declaration. For example:
final double PI = 3.14159;
final int STUDENTS_COUNT = 25;
• All final are static.
final static double PI = 3.14159;
Better than literal values because:
A. make code more readable by giving meaning to a value
B. use less memory, easy to modification (one place)14
Input and Output
• Java I/O is complicated.
1. Different kind of IO:
Files, console, block of memory, network
2. Different kinds of operations:
Sequential, random-access, binary,
character, integer, by lines, be words, ...
• Java provides a lot of classes to support IO.
Input and Output
• Java I/O is based on input streams and output streams
1. All classes inherit from IS have read methods.
2. All classes inherit from OS have write methods.
• There are three predefined standard streams:
Stream
Purpose
Default Device
System.in
System.out
System.err
reading input
writing output
writing errors
keyboard
monitor
monitor
• print and println methods write to
standard output
Input and Output
• Escape sequences: a special sequence of characters
preceded by a backslash (\)
Escape Sequence
Meaning
\t
\n
\"
\'
\\
tab
new line
double quote
single quote
backslash
17
Types of Output Stream
Writes to
ByteArrayOutputStrem
Block of Memory
FileOutputStrem
File
PipeOutputStrem
Pipe(to another thread)
18
Types of Input Stream
Reads from
ByteArrayInputStrem
Block of Memory
FileInputStrem
File
PipeInputStrem
Pipe(to another thread)
19
Input From Keyboard
• The Java API allows you to create many kinds of streams
to perform various kinds of I/O
• To read character strings, we will convert the
System.in stream to another kind of stream using:
BufferedReader stdin = new BufferedReader
(new InputStreamReader (System.in));
• This declaration creates a new stream called stdin
20
Echo.java
import java.io.*;
class Echo {
public static void main (String[] args) throws IOException {
BufferedReader stdin = new BufferedReader
(new InputStreamReader(System.in));
String message;
System.out.println ("Enter a line of text:");
message = stdin.readLine();
System.out.println ("You entered: \"" + message + "\"");
} // method main
} // class Echo
21
Open File
public class Scanner {
…
protected static DataInputStream inputStream;
Scanner(String fileName) throws IOException {
inputStream = new DataInputStream
(new FileInputStream (fileName));
}
…
22
}
Buffers
• As you type, the characters are stored in an input buffer
• When you press enter, the program begins processing
the data
• Output information is temporarily stored in an
output buffer
• The output buffer can be explicitly flushed
(sent to the screen) using the flush method
• See Python.java
23
Numeric Input
• Converting a string into the integer value:
value = Integer.parseInt(my_string);
• A value can be read and converted in one line:
num = Integer.parseInt(stdin.readLine());
C: scanf(“%d\n”, num);
24
Addition2.java
import java.io.*;
class Addition2 {
public static void main (String[] args) throws IOException {
BufferedReader stdin = new BufferedReader
(new InputStreamReader(System.in));
int num1, num2;
System.out.println ("Enter a number: ");
num1 = Integer.parseInt (stdin.readLine());
System.out.println ("Enter another number:");
num2 = Integer.parseInt (stdin.readLine());
System.out.println ("The sum is " + (num1+num2));
} // method main
25
} // class Addition2
Controlling Program Flow
• Essentially same as C/C++
• if statement:
if (condition)
Operator
statement;
• Relational operators:
==
!=
<
<=
>
<=
Meaning
equal to
not equal to
less than
less than or equal to
greater than
greater than or equal to
26
Controlling Program Flow
• if-else statement
if (condition)
statement1;
else
statement2;
• while statement:
while (condition)
statement;
Note: Avoid infinite loop (logic error)
27
Controlling Program Flow
• if-else statement
if (condition)
statement1;
else
statement2;
• while statement:
while (condition)
for statemetn:
for (e1;e2;e3)
statement;
Note: Avoid infinite loop (logic error)
statement;
28
import java.io.*;
class Right_Triangle { // bad bad bad RightTriangle
public static void main (String[] args) throws IOException {
BufferedReader stdin = new BufferedReader
(new InputStreamReader(System.in));
int hypotenuse_sq; // bad hypotenuseSquare
System.out.println ("Enter side 1:");
int side1 = Integer.parseInt (stdin.readLine());
System.out.println ("Enter side 2:");
int side2 = Integer.parseInt (stdin.readLine());
System.out.println ("Enter the hypotenuse:");
int side3 = Integer.parseInt (stdin.readLine());
hypotenuse_sq = (side1 * side1) + (side2 * side2);
if ((side3*side3) == hypotenuse_sq)
System.out.println ("It is a right triangle.");
else
System.out.println ("It is not a right triangle.");
29
} // method main
Conclusion
• primitive data types: predefined data types in Java
• Size of each primitive data type is machine independent
• Beware of scope(variables can not be redefined in blocks)
• Java I/O is complicated.
• IO is based input streams and output streams
完成 Lecture 3 休息十分鐘!
30