Basic I/O - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347,...

83
Basic I/O - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus Email: [email protected] 1 03/14/22

Transcript of Basic I/O - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347,...

Basic I/O - CIS 1068 Program Design and Abstraction

Zhen Jiang

CIS Dept.

Temple University

SERC 347, Main Campus

Email: [email protected]/19/23

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

204/19/23

http://www.cis.temple.edu/~jiang/Welcome.java http://www.cis.temple.edu/~jiang/Welcome1.java

Welcome – Your first program

304/19/23

Environment JDK (Java Development Kit) IDE (Integrated Development Environment) Installment guide

http://www.cis.temple.edu/~jiang/Installment1068.pdf Test run

404/19/23

5

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) Execute (java)

outputsource code(Hello.java)

byte code(Hello.class)

04/19/23

Details Names Main { } and ( ) Println and print (p93) ;

604/19/23

Textbook Highlighted by content in ppt slides Indexed by page number in ppt

slides Discussion Summary

Exercises (in ppt slides and class), assignment, quiz, test, final

04/19/23 8

Learning target www.cis.temple.edu/~jiang/ShowButtonDemo.pdf www.cis.temple.edu/~jiang/ButtonDemo.pdf www.cis.temple.edu/~jiang/WindowDestroyer.pdf

Three key topics Loop, (instance) method, and

text/string/array processing

04/19/23 9

Hello.java,

Simple Output

10

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 }

2 errors found:File: Hello.java [line: 2]Error: Hello.java:2: <identifier> expectedFile: Hello.java [line: 3]Error: Hello.java:3: ';' expected

compiler output:

04/19/23

11

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’”?04/19/23

12

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.

04/19/23

13

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:File: Hello.java [line: 1]Error: Hello.java:1: class, interface, or enum expected

compiler output:

04/19/23

14

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.

04/19/23

15

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.

04/19/23

16

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!"

04/19/23

17

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…04/19/23

18

A string can represent certain special characters by preceding them with a backslash \ (this is called an escape sequence, p89).

\t tab character \n newline character \" quotation mark character \\ backslash character

Example:System.out.println("Hello!\nHow are \"you\"?");

04/19/23

19

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):

/ \ // \\ /// \\\

04/19/23

20

What a println statement will generate the following output (one statement only)?

This program prints aquote from the Gettysburg Address.

"Four score and seven years ago,our 'fore fathers' brought forth on this continenta new nation."

What a println statement will generate the following output?

A "quoted" String is'much' better if you learnthe rules of "escape sequences."

Also, "" represents an empty String.Don't forget to use \" instead of " !'' is not the same as "

04/19/23

21

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.

04/19/23

22

… 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.

04/19/23

23

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.

04/19/23

Sample Program, P15 http://www.cis.temple.edu/~jiang/1068FirstProgram.pdf

Simple Input

2404/19/23

A piece of your computer's memory that is given a name and type and can store a value.

Usage compute an expression's result store that result into a variable use that variable later in the program

Variable

2504/19/23

26

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;

04/19/23

27

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: ?

(You know! The memory has an uncertain value.)04/19/23

28

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)

04/19/23

Name, p103 Begin with [a]-[Z], _, or $ Contain only [a]-[Z], [0]-[9], _, and $ No keyword Case distinct “punctuate”, capital letter or ‘_’, page 104

2904/19/23

30

Examples: legal: susan second_place _myName

TheCure ANSWER_IS_42 $variablemethod1 myMethod name2

illegal: me+u 49er question? side-swipe hi there ph.d

jim's 2%[email protected]

04/19/23

31

keyword: An identifier that you cannot use, because it already has a reserved meaning in the Java language.

Complete list of Java keywords: abstract default if private this boolean do implements protected throw break double import public throws byte else instanceof return transient case extends int short try catch final interface static void char finally long strictfp volatile class float native super while const for new switch continue goto package synchronized

NB: Because Java is case-sensitive, you could technically use Class or cLaSs as identifiers, but this is very confusing and thus strongly discouraged.

04/19/23

32

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!

04/19/23

33

Java has eight primitive types. Here are two examples:

Name Description Examplesint integers 42, -3, 0, 926394double real numbers 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?04/19/23

Temperature Sum of a group of integers Average of a group of integers Number of seconds left in a game

3404/19/23

Lesson two: Are you able to handle the data that

is out of the original plan? What a kind (type) of data is in use? Should it be changed to new type? What is the new type?

3504/19/23

36

Discrete Typesbyteshortintlong

Continuous Typesfloat

double

Non-numeric Typesboolean

char

04/19/23

Type Representation

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

6404/19/23 37

Arithmetic (Use of variables) 17/3=? http://www.cis.temple.edu/~jiang/

Variable.pdf

3804/19/23

39

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.25myGPA = 3.25;

04/19/23

40

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

04/19/23

41

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?

04/19/23

42

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

04/19/23

43

The assignment statement is not an algebraic equation!

<variable> = <expression>; means: "store the value of <expression> into <variable>” Some people read x = 3 * 4; as "x gets the value of 3 * 4"

ERROR: 3 = 1 + 2; is an illegal statement, because 3 is not a variable.

ERROR: a = 1 + * 2; is an illegal statement, because the expression is incomplete.04/19/23

44

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;

04/19/23

char

int

byte

long

short

double

float

boolean

04/19/23 45

46

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

04/19/23

47

Arithmetic operators we will use: + addition - subtraction or negation * multiplication / division % modulus, a.k.a. remainder

04/19/23

48

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?

04/19/23

49

When dividing integers, the result is also an integer: the quotient.

Example: 17 / 3 evaluates to 5, not 5.666666 (truncate the decimal part)

Examples: 35 / 5 is 7 84 / 10 is 8 156 / 100 is 1 24 / 0 is illegal (what do you think happens?)

04/19/23

50

The modulus computes the remainder from a division of integers.

Example: 14 % 4 is 21425 % 27 is 21

3 52 4 ) 14 27 ) 1425 12 135 2 75 54 21 What are the results of the following expressions?

45 % 6 4 % 2 8 % 20 11 % 004/19/23

51

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.

From 73.425, obtain the 73.43.

04/19/23

52

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

+ -Addition, Subtraction

* / %Multiplication, Division, Mod

()Parentheses

04/19/23

53

1 * 2 + 3 * 5 / 4 \_/

| 2 + 3 * 5 / 4

\_/ | 2 + 15 / 4

\___/ | 2 + 3

\________/ | 5

1 + 2 / 3 * 5 - 4 \_/

|1 + 0 * 5 - 4

\___/ |1 + 0 - 4

\______/ | 1 - 4

\_________/ | -3

04/19/23

54

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.61 / 2.0 is 0.5

Type cast (p65) Examples:

(int)4.2 is 4(double)17 is 17.0

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.

04/19/23

55

String concatenation: Using the + operator between a string and another value to make a longer string.

Examples:"hello" + 42 is "hello42"1 + "abc" + 2 is "1abc2""abc" + 1 + 2 is "abc12"1 + 2 + "abc" is "3abc""abc" + 9 * 3 is "abc27" (what happened here?)"1" + 1 is "11"4 - 1 + "abc" is "3abc"

"abc" + 4 - 1 causes a compiler error. Why?04/19/23

56

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: 249.6

Your average: 83.2

04/19/23

57

The computer internally represents real numbers in an imprecise way.

Example:System.out.println(0.1 + 0.2); The output is 0.30000000000000004!

04/19/23

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?

04/19/23 58

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.

04/19/23 59

int n = 2000000000;

System.out.println(n * n);

// output: -1651507200

04/19/23 60

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.

04/19/23 61

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.

04/19/23 62

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

6304/19/23

64

Shorthand Equivalent longer version<variable>++; <variable> = <variable> + 1;<variable>--; <variable> = <variable> - 1;

Examples:int x = 2;x++; // x = x + 1;

// x now stores 3

double gpa = 2.5;gpa++; // gpa = gpa + 1;

// gpa now stores 3.5

04/19/23

after executingint m = 4;int result = 3 * (++m)result has a value of 15 and m has a value of 5

after executingint m = 4;int result = 3 * (m++)

result has a value of 12 and m has a value of 5

04/19/23 65

66

Java has several combined operators that allow you to quickly modify a variable's value.

Shorthand Equivalent longer version<variable> += <exp>; <variable> = <variable> + (<exp>);<variable> -= <exp>; <variable> = <variable> - (<exp>);<variable> *= <exp>; <variable> = <variable> * (<exp>);<variable> /= <exp>; <variable> = <variable> / (<exp>);<variable> %= <exp>; <variable> = <variable> % (<exp>);

Examples: x += 3 - 4; // x = x + (3 - 4); gpa -= 0.5; // gpa = gpa – (0.5); number *= 2; // number = number * (2);04/19/23

67

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;

04/19/23

68

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.

04/19/23

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. http://www.cis.temple.edu/~jiang/CircleCalculation2.pdf

04/19/23 69

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.

04/19/23 70

Syntaxpublic static final Variable_Type <name> = <Constant>;

Examplespublic static final double PI = 3.14159;

public static final String MOTTO = "The customer is always right.";

By convention, uppercase letters are used for constants.

04/19/23 71

Swap.java http://www.cis.temple.edu/~jiang/

Swap.pdf Payroll.java

http://www.cis.temple.edu/~jiang/Payroll.pdf

7204/19/23

Math.PI, Math.pow, Math.sqrt, etc. (p412)

7304/19/23

74

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”

String

04/19/23

75

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); // prints SSystem.out.println((int)letter); // prints 83,

// explained on p93204/19/23

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).

04/19/23 76

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”; // declare, init

System.out.println(s); // use value

s = s + “I am your master\n”; // concatenate

// and assign

04/19/23 77

78

Unlike primitive types, String can have methods, P86.

Here is a list of methods for strings:

returns the index where the start of the given string appears in this string (-1 if not found)

indexOf(str)

returns a new string with all uppercase letterstoUpperCase()

returns a new string with all lowercase letterstoLowerCase()

returns the characters in this string from index1 up to, but not including, index2

substring(index1,index2)

returns the number of characters in this stringlength()

returns the character at the given indexcharAt(index)

DescriptionMethod name

04/19/23

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”

04/19/23 79

Displaying message Input P116-118

converting a string to number, p123 Output P121-122

converting a number to string http://www.cis.temple.edu/~jiang/Payroll2.pdf

8004/19/23

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)

Summary of programs in discussion

8104/19/23

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

Summary of Concepts

8204/19/23

Printf (p101) Delimiters for input (p99) Windows program (p125)

http://www.cis.temple.edu/~jiang/ChangeMakerWindow.pdf

Other materials (FYI, not required for test)

8304/19/23