Input, output, variable, assignment, calculation
Download
Report
Transcript Input, output, variable, assignment, calculation
Basic I/O - CIS 1068
Program Design and Abstraction
Zhen Jiang
CIS Dept.
Temple University
1008 Wachman Hall, Main Campus
Email: [email protected]
4/13/2015
1
Table of Contents
Your first Java program
Simple Output/Input
Variable
Data types
Arithmetic (use of variables)
String and its use in I/O statement
Summary of programs
Summary of concepts
Other materials
4/13/2015
2
Welcome – Your first program
http://www.cis.temple.edu/~jiang/Welcome.java
http://www.cis.temple.edu/~jiang/Welcome1.java
4/13/2015
3
Environment
JDK (Java Development Kit)
IDE (Integrated Development Environment)
Installment guide
http://www.cis.temple.edu/~jiang/Installment1068.pdf
Test run
4/13/2015
4
Before you run a program, you must compile it.
compiler: Translates a computer program written in one
language (i.e., Java) to another language (i.e., byte code)
Compile (javac)
source code
(Hello.java)
4/13/2015
Execute (java)
byte code
(Hello.class)
output
5
Details
Names
Main
{ } and ( )
Println and print (p93)
;
4/13/2015
6
Textbook
Highlighted by content in ppt slides
Indexed by page number in ppt slides
Discussion
Summary
Exercises (in ppt slides and class), quiz,
project, test, final
Take a lesson from the learning in a
previous section
Learning target
http://www.cis.temple.edu/~jiang/CIS1068_07_summary.pdf
www.cis.temple.edu/~jiang/ShowButtonDemo.pdf
www.cis.temple.edu/~jiang/ButtonDemo.pdf
www.cis.temple.edu/~jiang/WindowDestroyer.pdf
Three keys
4/13/2015
Loop, (instance) method, and text/string
processing
8
Simple Output
Hello.java,
syntax error: A problem in the structure of a program.
1 public class Hello {
2
pooblic static void main(String[] args) {
3
System.owt.println("Hello, world!")
4
}
5 }
compiler output:
2 errors found:
File: Hello.java [line: 2]
Error: Hello.java:2: <identifier> expected
File: Hello.java [line: 3]
Error: Hello.java:3: ';' expected
4/13/2015
9
Error messages do not always help us
understand what is wrong:
File: Hello.java [line: 2]
Error: Hello.java:2: <identifier> expected
pooblic static void main(String[] args) {
Why can’t the computer just say “You
misspelled ‘public’”?
4/13/2015
10
First lesson
Computers can’t read minds.
Computers don’t make mistakes.
If the computer is not doing what you want, it’s because
YOU made a mistake.
4/13/2015
11
Java is case-sensitive
Public and public are not the same
1 Public class Hello {
2 public static void main(String[] args) {
3 System.out.println("Hello, world!");
4 }
5}
1 error found:
compiler output:
File: Hello.java [line: 1]
Error: Hello.java:1: class, interface, or enum expected
4/13/2015
12
System.out.println: A statement to print a line of output.
pronounced “print-linn”
The use of System.out.println (P93) :
System.out.println("<message>");
Prints the given message as a line of text.
System.out.println(<number>);
Prints the given number as a line of text.
4/13/2015
13
System.out.println(<output1> + <output2>+… +<output_Last>);
Performs a output string concatenation and prints all as a line of
text.
System.out.println();
Prints a blank line.
4/13/2015
14
String: A sequence of text characters, also
called message.
Start and end with quotation mark characters
Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
4/13/2015
15
A string may not span across multiple lines.
"This is not
a legal string."
A string may not contain a “ character.
The ‘ character is okay.
"This is not a "legal" string either."
"This is 'okay' though."
This begs the question…
4/13/2015
16
A string can represent certain special characters by
preceding them with a backslash \ (this is called an
escape sequence, p89).
\t
\n
\"
\\
tab character
newline character
quotation mark character
backslash character
Example:
System.out.println("Hello!\nHow are \"you\"?");
4/13/2015
17
What is the output of each of the following println
statements?
System.out.println("\ta\tb\tc");
System.out.println("\\\\");
System.out.println("'");
System.out.println("\"\"\"");
System.out.println("C:\nin\the downward spiral");
Write a println statement to produce the following line of
output (space counted):
/ \ // \\ /// \\\
4/13/2015
18
What a println statement will generate the following output (one statement
only)?
This program prints a
quote from the Gettysburg Address.
"Four score and seven years ago,
our 'fore fathers' brought forth on this continent
a new nation."
What a println statement will generate the following output?
A "quoted" String is
'much' better if you learn
the rules of "escape sequences."
Also, "" represents an empty String.
Don't forget to use \" instead of " !
'' is not the same as "
4/13/2015
19
comment: A note written in the source code to make the code easier
to understand (p104).
Comments are not executed when your program runs.
Most Java editors show your comments with a special color.
Comment, general syntax:
/* <comment text; may span multiple lines> */
or,
// <comment text, on one line>
Examples:
/* A comment goes here. */
/* It can even span
multiple lines. */
// This is a one-line comment.
4/13/2015
20
… at the top of each file (also called a "comment header"), naming
the author and explaining what the program does.
… at the start of every method, describing its behavior or function.
… inside methods, to explain the complex pieces of code.
4/13/2015
21
Comments provide important documentation.
Comments provide a simple description of what each class, method,
etc. is doing.
Later programs will span hundreds or thousands of lines, split into
many classes and methods.
When multiple programmers work together, comments help one
programmer understand the other's code.
4/13/2015
22
Simple Input
Sample Program, P15
http://www.cis.temple.edu/~jiang/1068FirstProgram.pdf
4/13/2015
23
Variable
A piece of your computer's memory that is given
a name and type and can store a value.
Usage
4/13/2015
compute an expression's result
store that result into a variable
use that variable later in the program
24
To use a variable, it must be declared.
Variable declaration syntax (P51):
<type> <name>;
Convention: Variable identifiers follow the same rules as
method names.
Examples:
int x;
double myGPA;
int varName;
4/13/2015
25
Declaring a variable sets aside a piece of
memory in which you can store a value.
int x;
int y;
Inside the computer:
x: ?
y: ?
(The memory still has no value yet.)
4/13/2015
26
identifier: A name given to an entity in a program such as a class or
method.
Identifiers allow us to refer to the entities.
Examples (in bold):
public class Hello
public static void main
double salary
Conventions for naming in Java (which we will follow):
classes: capitalize each word (ClassName)
everything else: capitalize each word after the first (myLastName)
4/13/2015
27
Name, p103
4/13/2015
Begin with [a]-[Z], _, or $
Contain only [a]-[Z], [0]-[9], _, and $
No keyword
Case distinct
“punctuate”, page 104
28
Examples:
legal:susan
TheCure
myMethod
second_place _myName
ANSWER_IS_42 $variable
name2
illegal: me+u
side-swipe
jim's
49er
question?
hi there ph.d
2%milk [email protected]
4/13/2015
method1
29
keyword: An identifier that you cannot use, because it already has a
reserved meaning in the Java language.
Complete list of Java keywords:
abstract
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
NB: Because Java is case-sensitive, you could technically use Class or cLaSs
as identifiers, but this is very confusing and thus strongly discouraged.
4/13/2015
30
Data types
data type: A category of data values.
Example: integer, real number, string
Data types are divided into two classes:
primitive types: Java's built-in simple data types
for numbers, text characters, and logic.
class types: type of objects, coming soon!
4/13/2015
31
Java has eight primitive types. Here are two examples:
Name Description
int
integers
double
real numbers
Examples
42, -3, 0, 926394
3.4, -2.53, 91.4e3
Numbers with a decimal point are treated as real numbers.
Question: Isn’t every integer a real number? Why bother?
4/13/2015
32
Temperature
Sum of a group of integers
Average of a group of integers
Number of seconds left in a game
4/13/2015
33
Lesson two:
Are you able to handle the data that is out
of the original plan?
4/13/2015
What a kind (type) of data is in use?
Should it be changed to new type?
What is the new type?
34
Discrete Types
byte
short
int
long
4/13/2015
Continuous Types
float
double
Non-numeric Types
boolean
char
35
Type
Representatio
n
Bits
Bytes
#Values
boolean
True or False
1
N/A
2
char
‘a’ or ‘7’ or ‘\n’
16
2
216 = 65,536
byte
…,-2,-1,0,1,2,…
8
1
28 = 256
short
…,-2,-1,0,1,2,…
16
2
216 = 65,536
int
…,-2,-1,0,1,2,…
4
> 4.29 million
long
…,-2,-1,0,1,2,…
8
> 18
quintillion
float
0.0, 10.5, -100.7
32
double
0.0, 10.5, -100.7
64
4/13/2015
36
Arithmetic (Use of variables)
17/3=?
http://www.cis.temple.edu/~jiang/Variable.
pdf
4/13/2015
37
Assignment statement: A Java statement that stores a value into a
variable.
Variables must be declared before they can be assigned a value.
Assignment statement syntax:
<variable> = <expression>;
Examples:
x = 2 * 4;
x: 8
myGPA = 3.25;
4/13/2015
myGPA: 3.25
38
A variable can be assigned a value more than once.
Example:
int x;
x = 3;
System.out.println(x);
// 3
x = 4 + 7;
System.out.println(x);
// 11
4/13/2015
39
Once a variable is assigned a value, it can be used in any expression.
int x;
x = 2 * 4;
y = x +3;
System.out.println(x * 5 - 1);
The above has output equivalent to:
System.out.println(8 * 5 - 1);
What happens when a variable is used on both sides of an assignment
statement ?
int x;
x = 3;
x = x + 2; // what happens?
4/13/2015
40
ERROR: Declaring two variables with the same name
Example:
int x;
int x;
// ERROR: x already exists
ERROR: Reading a variable’s value before it has been
assigned
Example:
int x;
System.out.println(x); // ERROR: x has no value
4/13/2015
41
The assignment statement is not an algebraic equation!
<variable> = <expression>; means:
Some people read x = 3 * 4; as
"store the value of <expression> into <variable>"
"x gets the value of 3 * 4"
ERROR: 3 = 1 + 2; is an illegal statement, because 3
is not a variable.
4/13/2015
42
A variable can only store a value of its own type.
Example:
int x;
x = 2.5;
// ERROR: x can only store int
An int value can be stored in a double variable. Why?
Type compatibility: The value is converted into the equivalent
real number (p64).
Example:
double myGPA;
myGPA: 2.0
myGPA = 2;
4/13/2015
43
double
float
long
int
char
boolean
short
byte
4/13/2015
44
Manipulating data via expressions
Expression: A data value or a set of operations that
produces a value.
Examples:
1+4*3
3
"CSE142"
(1 + 2) % 3 * 4
4/13/2015
45
Arithmetic operators we will use:
+
*
/
%
4/13/2015
addition
subtraction or negation
multiplication
division
modulus, a.k.a. remainder
46
When Java executes a program and encounters an
expression, the expression is evaluated (i.e., computed).
Example:
3 * 4 evaluates to 12
System.out.println(3 * 4) prints 12 (after evaluating 3 * 4)
How could we print the text 3 * 4?
4/13/2015
47
When dividing integers, the result is also an integer: the quotient.
Example: 14 / 4 evaluates to 3, not 3.5 (truncate the decimal part)
Examples:
1425 / 27 is 52
35 / 5 is 7
84 / 10 is 8
156 / 100 is 1
24 / 0 is illegal (what do you think happens?)
4/13/2015
48
The modulus computes the remainder from a division of
integers.
Example: 14 % 4 is 2
1425 % 27 is 21
3
4 ) 14
12
2
52
27 ) 1425
135
75
54
21
What are the results of the following expressions?
45 % 6
4 % 2
8 % 20
11 % 0
4/13/2015
49
What expression obtains (ChangeMaker.java, P77)
the last digit (unit’s place) of a number?
Example: From 230857, obtain the 7.
the last 4 digits of a Social Security Number?
Example: From 658236489, obtain 6489.
the second-to-last digit (ten’s place) of a number?
Example: From 7342, obtain the 4.
the part of a number rounded off to the nearest hundredth?
Example: From 73.424, obtain the 73.42.
From 73.425, obtain the 73.42.
the part of a number rounded up to the nearest hundredth?
Example: From 73.424, obtain the 73.42.
4/13/2015
50
From 73.425, obtain the 73.43.
Precedence: Order in which operations are computed in an
expression.
Operators on the same level are evaluated from left to right.
Example:
1 - 2 + 3 is 2 (not -4)
Spacing does not affect order of evaluation.
Example:
1+3 * 4-2 is 11
Parentheses
Multiplication, Division, Mod
Addition, Subtraction
4/13/2015
()
* / %
+ 51
1 * 2 + 3 * 5 / 4
\_/
|
2
+ 3 * 5 / 4
\_/
|
2
+ 15
/ 4
\___/
|
2
+
3
\________/
|
5
4/13/2015
1 + 2 / 3 * 5 - 4
\_/
|
1 +
0
* 5 - 4
\___/
|
1 +
0
- 4
\______/
|
1
- 4
\_________/
|
-3
52
When an operator is used on
an integer and a real number,
the result is a real number
(Type compatibility, p64).
Examples:
4.2 * 3 is 12.6
1 / 2.0 is 0.5
Type cast (p65)
Examples:
(int)4.2 is 4
(double)17 is 17.0
4/13/2015
7 / 3 * 1.2 + 3 / 2
\_/
|
2
* 1.2 + 3 / 2
\___/
|
2.4
+ 3 / 2
\_/
|
2.4
+
1
\________/
|
3.4
Notice how 3 / 2 is still
1 above, not 1.5.
53
String concatenation: Using the + operator between a string
and another value to make a longer string.
Examples:
"hello" + 42 is
1 + "abc" + 2is
"abc" + 1 + 2is
1 + 2 + "abc"is
"abc" + 9 * 3is
"1" + 1is "11"
4 - 1 + "abc"is
"hello42"
"1abc2"
"abc12"
"3abc"
"abc27" (what happened here?)
"3abc"
"abc" + 4 - 1causes a compiler error. Why?
4/13/2015
54
Write a program to print out the following output.
Use math expressions to calculate the last two numbers.
Your grade on test 1 was 95.1
Your grade on test 2 was 71.9
Your grade on test 3 was 82.6
Your total points:
Your average:
4/13/2015
249.6
83.2
55
The computer internally represents real
numbers in an imprecise way.
Example:
System.out.println(0.1 + 0.2);
The output is 0.30000000000000004!
4/13/2015
56
ints are stored in 4 bytes (32 bits)
In 32 bits, we can store at most 232 different
numbers
What happens if we take the largest of these,
and add 1 to it?
4/13/2015
57
ERROR!
This is known as overflow: trying to store
something that does not fit into the bits reserved
for a data type.
http://en.wikipedia.org/wiki/Arithmetic_overflow
Overflow errors are NOT automatically detected!
It’s the programmer’s responsibility to prevent these.
The actual result in this case is a negative number.
4/13/2015
58
int n = 2000000000;
System.out.println(n * n);
// output: -1651507200
4/13/2015
59
the result of n*n is 4,000,000,000,000,000,000 which needs 64-bits:
---------- high-order bytes ------00110111 10000010 11011010 11001110
---------- low order bytes -------10011101 10010000 00000000 00000000
In the case of overflow, Java discards the high-order bytes, retaining
only the low-order ones
In this case, the low order bytes represent 1651507200, and since the
right most bit is a 1 the sign value is negative.
4/13/2015
60
What happens if we create a double value of 1, and then
keep dividing it by 10?
Answer: eventually, it becomes 0.
This is known as underflow: a condition where a
calculated value is smaller than what can be represented
using the number of bytes assigned to its type
http://en.wikipedia.org/wiki/Arithmetic_underflow
Again, Java does not detect this error; it’s up to the
programmer to handle it.
4/13/2015
61
Legal assignment
Left is a single variable
Right is a legal expression
Prefix and postfix increment/decrement,
p79
Combined assignment, p73
Initialization & Declaration, p57
Constants (i.e., final), P60
4/13/2015
62
Shorthand
<variable>++;
<variable>--;
Examples:
int x = 2;
x++;
Equivalent longer version
<variable> = <variable> + 1;
<variable> = <variable> - 1;
// x = x + 1;
// x now stores 3
double gpa = 2.5;
gpa++;
// gpa = gpa + 1;
// gpa now stores 3.5
4/13/2015
63
after executing
int m = 4;
int result = 3 * (++m)
result has a value of 15 and m has a value of 5
after executing
int m = 4;
int result = 3 * (m++)
result has a value of 12 and m has a value of 5
4/13/2015
64
Java has several combined operators that allow you to quickly
modify a variable's value.
Shorthand
<variable>
<variable>
<variable>
<variable>
<variable>
+=
-=
*=
/=
%=
Equivalent longer version
<exp>;
<variable> =
<exp>;
<variable> =
<exp>;
<variable> =
<exp>;
<variable> =
<exp>;
<variable> =
<variable>
<variable>
<variable>
<variable>
<variable>
+
*
/
%
(<exp>);
(<exp>);
(<exp>);
(<exp>);
(<exp>);
Examples:
x += 3 - 4;
gpa -= 0.5;
number *= 2;
4/13/2015
// x = x + (3 - 4);
// gpa = gpa – (0.5);
// number = number * (2);
65
A variable can be declared and assigned
an initial value in the same statement.
Declaration/initialization statement syntax:
<type> <name> = <expression>;
Examples:
double myGPA = 3.95;
int x = (11 % 3) + 12;
4/13/2015
66
It is legal to declare multiple variables on one line:
<type> <name>, <name>, ..., <name>;
Examples:
int a, b, c;
double x, y;
It is also legal to declare/initialize several at once:
<type> <name> = <expression> , ..., <name> =
<expression>;
Examples:
int a = 2, b = 3, c = -4;
double grade = 3.5, delta = 0.1;
NB: The variables must be of the same type.
4/13/2015
67
To avoid confusion, always name constants
(and variables).
area = PI * radius * radius;
is clearer than
area = 3.14159 * radius * radius;
Place constants near the beginning of the
program, CircleCalculation2.java, p108.
4/13/2015
http://www.cis.temple.edu/~jiang/CircleCalculation2.pdf
68
Once the value of a constant is set (or
changed by an editor), it can be used (or
reflected) throughout the program.
public static final double INTEREST_RATE =
6.65;
If a literal (such as 6.65) is used instead,
every occurrence must be changed, with the
risk than another literal with the same value
might be changed unintentionally.
4/13/2015
69
Syntax
public static final
Variable_Type <name> = <Constant>;
Examples
public static final double
PI = 3.14159;
public static final String MOTTO =
"The customer is always right.";
By convention, uppercase letters are used for
constants.
4/13/2015
70
Swap.java
http://www.cis.temple.edu/~jiang/Swap.pdf
Payroll.java
http://www.cis.temple.edu/~jiang/Payroll.pdf
4/13/2015
71
Math.PI, Math.pow, Math.sqrt, etc. (p412)
4/13/2015
72
String
text processing: Two data types involved
char
String
Represents individual characters
Represents sequences of characters
Primitive type
Object type (i.e., not primitive)
Written with single quotes
Written with double quotes
e.g.:
‘T’
‘t’
‘3’
‘%’
‘\n’
e.g.:
“We the people”
“1. Twas brillig, and the slithy toves\n”
“”
“T”
4/13/2015
73
char: A primitive type representing single characters. P52.
Individual characters inside a String are stored as char
values.
Literal char values are surrounded with apostrophe
(single-quote) marks, such as 'a' or '4' or '\n' or
'\''
Example, p67.
char letter = 'S';
System.out.println(letter);
System.out.println((int)letter);
4/13/2015
// prints S
// prints 83,
// explained on p932
74
Most programming languages use the ASCII
character set.
Java uses the Unicode character set which
includes the ASCII character set.
The Unicode character set includes characters
from many different alphabets (but you
probably won't use them).
4/13/2015
75
String: an object type for representing sequences
of characters
Sequence can be of length 0, 1, or longer
Each element of the sequence is a char
We write strings surrounded in double-quotes
We can declare, initialize, assign, and use String variables
in expressions just like other data types
String s = “Hello, world\n”;
System.out.println(s);
s = s + “I am your master\n”;
4/13/2015
//
//
//
//
declare, init
use value
concatenate
and assign
76
Unlike primitive types, String can have methods, P86.
Here is a list of methods for strings:
Method name
Description
charAt(index)
returns the character at the given index
indexOf(str)
returns the index where the start of the given string appears in this
string (-1 if not found)
length()
returns the number of characters in this string
substring(index1,index2)
returns the characters in this string from index1 up to, but not
including, index2
toLowerCase()
returns a new string with all lowercase letters
toUpperCase()
returns a new string with all uppercase letters
4/13/2015
77
Let s be a variable of type String
General syntax for calling a String method:
s.<method>(<args>)
Some examples:
String s = “Cola”;
int len = s.length();
// len == 4
char firstLetter = s.charAt(0); // ‘C’
int index = s.indexOf(“ol”); // index == 1
String sub = s.substring(1,3); // “ol”
String up = s.toUpperCase(); // “COLA”
String down = s.toLowerCase(); // “cola”
4/13/2015
78
Displaying message
Input P116-118
converting a string to number, p123
Output P121-122
converting a number to string
4/13/2015
http://www.cis.temple.edu/~jiang/Payroll2.pdf
79
Summary of programs in
discussion
Welcome.java
Welcome.java
Hello.java
Exercises (slide 17-18, 49, 54)
FirstProgram.java
Variable.java
ChangeMaker.java
CircleCalculation2.java
Swap.java
Payroll.java
Payroll2.java (a similar program ChangeMakerWindow.java)
4/13/2015
80
Summary of Concepts
Running environment and execution of program (see lab work)
Template of java program, i.e., file, class, and main (see in lab work)
Program debug (memory tracking)
println and print (P93), escape sequence (P89)
Input via keyboard and plain text output (P96-97)
I/O via JOptionPane (showInputDialog P116-8, showMessageDialog P121-2)
Variable (P50-1), name (P55, P103), assignment (P55), declaration (P51), type
(P52), initialization (P57)
Constants (P60), type compatibility (P63-4) and type cast (P65-66)
String, its conversion to number P123 and vice versa (concatenation P82)
Arithmetic operators (e.g., %, P68), precedence order (P72)
Imprecision (round-off error), and overflow (online materials)
Prefix and postfix increment/decrement (P78,79), combined assignment (P73)
Math class, P410-413
4/13/2015
81
Other materials (FYI, not
required for test)
Printf (p101)
Delimiters for input (p99)
Windows program (p125)
http://www.cis.temple.edu/~jiang/ChangeMakerWind
ow.pdf
4/13/2015
82