Top Banner
CS 241 CS 241 – Computer Programming II Computer Programming II Acknowledgements: These slides were created by Dr. Travis Doom with information, graphics, materials, or kindly aid provided by Gaddis’s “Starting Out with Java”, McConnell’s “Code Complete”, Sierra’s “Head First Java”, Guzdal’s 1 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II “Introduction to computing and programming with Java”, and Barnes’s “Objects First with Java”.
28

CS 241 CS 241 - Wright

Apr 27, 2022

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CS 241 CS 241 - Wright

CS 241 CS 241 –– Computer Programming IIComputer Programming II

Acknowledgements: These slides were created by Dr. Travis Doom with information, graphics, materials, or kindly aid provided by Gaddis’s “Starting Out with Java”, McConnell’s “Code Complete”, Sierra’s “Head First Java”, Guzdal’s

1Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

p y g , p , ,“Introduction to computing and programming with Java”, and Barnes’s “Objects First with Java”.

Page 2: CS 241 CS 241 - Wright

Programming basicsProgramming basicsProgramming basicsProgramming basics(review)(review)

Computer programmingp p g gSemantics, syntax, and style

Variables and data typeMethods and decomposition

Methods for I/O in Java

Page 3: CS 241 CS 241 - Wright

Am I in the right place?Am I in the right place?

What is computer programming?What is computer science?What is computer science?Why study computer science/programming?– Drives innovation in sciences (makes a positive difference!)– Foundational knowledge in problem solving and logical thinking– The “renaissance man” knowledge-base of the 21st century– Computing jobs rated among highest paying and most satisfying

Lots of teamwork! Good communication skills mandatory!

– Greatest job growth area (contrary to popular belief)– Its impossible to predict what will happen next in computing, there are p p pp p g,

constantly new opportunities to make new, significant contributions

3Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Page 4: CS 241 CS 241 - Wright

CS 241: The big pictureCS 241: The big picture

Prior to this class you should have learned how to:– create an executable program (semantics, syntax, and style)p g ( , y , y )– create and use typed variables to store primitive and reference values– use standard operators to manipulate variable and literal values

decompose a design using routines (methods) iteration and selection– decompose a design using routines (methods), iteration, and selection– manage simple collections of data (arrays and ArrayLists)– handle basic console and file I/O tasks

In this class you will learn how to:– create/design your own classes and objects– decompose a design by developing object types (when and why!)p g y p g j yp ( y )– create, test, debug, and manage applications of moderate complexity– to use more sophisticated library objects and interfaces

Including libraries to manage events threads and graphics

4Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Including libraries to manage events, threads, and graphics

Page 5: CS 241 CS 241 - Wright

Computer programmingComputer programming

Essentially, computers are simple devices that:

Memory

MAR MDRsimple devices that:– allow input to memory– allow output from memory

ll li it d i

Processing Unit

Input OutputALU TEMP

C l U i(keyboard) (monitor)– allow limited processing

(instructions) on memory Computer programming is the t k f i th li it d

Control Unit

PC IR

( )

task of sequencing the limited processing operations towards solving a specific design goal.Hi h l l l ll

Computer A

Compilersource code

t bl

syntax errors

warnings

com

pile

tim

e

High level languages allow us to specify tasks without being aware of the specific instructions need on a system

Computer A

OSinput from user output to user display

inputs from fil / k/

output to files/networks/etc

executable program

run

time

c

5Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

instructions need on a system. files/network/etc

Page 6: CS 241 CS 241 - Wright

Compilation Vs. InterpretationCompilation Vs. Interpretation

Compilersource code syntax errors

warnings tion

A lt ti t ili i t i t t

Computer Ainput from user output to user display

inputs from files/network/etc

output to files/networks/etc

warnings

inte

rpre

tat

An alternative to compiling your program is to interpret your program– each line of your program is translated into a machine language and

immediately executedLike translating between natural languages– Compiler: human translator translates book in its entirety and then

translated book is printed (compiled to executable format). That book can THEN be stored and read (executed) without repeating the process.

– Interpreter: human interpreter translates each spoken statement in sequence AS speaker is speaking. No recording of the translated

6Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

version is made. It must be re-interpreted to hear it again.

Page 7: CS 241 CS 241 - Wright

Compiling to a virtual machineCompiling to a virtual machine

Java uses both compilation and interpretation in a two-step processCompiles program into bytecode

Compilersource code syntax errors

warnings time

Compiles program into bytecode– bytecode is a generic “machine

language” for a “virtual machine”– does not correspond to any particular

machine

Computer A

Virtual

bytecode

warnings

ion

com

pile

Virtual Machine (VM) interprets bytecodes into native machine language and runs it

– different VM implementation exists for each native computer machine language

Computer A

Machineinput from user output to user display

inputs from files/network/etc

output to files/networks/etc

inte

rpre

tati

Same Java bytecodes can be used on different computers without re-compiling source code

– each VM interprets same bytecodes– allows you to run Java programs by

Computer A

Compilersource code syntax errors

warnings

ompi

le ti

me

getting just bytecodes from Web pageThis makes Java code run cross-platform

– “Write once, run anywhere!”Computer B

Virtual Machine

input from user output to user display

inputs from output to files/networks/etc

bytecode

erpr

etat

ion

co

7Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

inputs from files/network/etc in

te

Page 8: CS 241 CS 241 - Wright

Why Java?Why Java?

Java is VERY object-orientedJava is popular in the fieldJava is popular in the field– Early versions of Java were slow, buggy, and hard to use.– Platform independence still made it amazingly popular– Current versions of Java have most/all features that are popular in

other programming languages– Java and C++ are close cousins

Java run complete with thousands of library classes, nearly everywhere– More power! Easier to develop with! Powerful (and free) IDEs!

Although the fundamental concepts of this course apply to ALL oug e u da e a co cep s o s cou se app y oprogramming, the specifics we will use for illustration and for formative/summative experiences will be in JavaIf you’ve never used Java before, talk to your instructor ASAP

8Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

y , y

Page 9: CS 241 CS 241 - Wright

Semantics, Syntax, and StyleSemantics, Syntax, and Style

public class HelloWorld {public static void main (String[] args) {

System.out.println(“Hello World”);} // end method main

} // end class HelloWorld

Semantics – the “meaning”When programming we to should focus on semantics.

Syntax – the rules that must be followed when writing a programy g p gIn algebra, what is “5 + 3”? What is “5-”?Programming language syntax rules are like grammar rules in natural/spoken languages. Syntax differs by language!p g g y y g gSyntax rules are required to avoid ambiguity.Compilers/IDEs help identify syntax errors but, like grammar, they must largely be memorized

9Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Style – conventions that affect the readability of the program

Page 10: CS 241 CS 241 - Wright

Code structure in JavaCode structure in Java

public class HelloWorld {public static void main (String[] args) {

System.out.println(“Hello World”);} // end method main

} // end class HelloWorld

Put a class in a source file- A source code file (with a .java extension) holds one class definition- So far you may have only used once class (and thus one file)y y y ( )- In general, each class is just a piece (unit) of the application

Put each method in a class- Methods are used to perform specific tasksMethods are used to perform specific tasks- Exactly one “main” method must exist in your source file(s)

Put statements in each method- Finally we actually get to DO something!

10Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Finally, we actually get to DO something!

Page 11: CS 241 CS 241 - Wright

Control flowControl flow

Do somethingSequential execution

f

Do something under this condition

Do again and againIteration

of statements…statement1;statement2;

conditionSelection

…if (condition) {

…while (condition) {statement(s);

}state e t ;…

{

statement(s);}-or-

}-or-for (initializer;

condition; update // a block of// statements are// treated as// one statement

if (condition) {statement(s);

} else {statement(s);

expression) {statement(s);

}-or-// one statement

}

statement(s);}…

ordo {

statement(s);} while (condition)

11Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Page 12: CS 241 CS 241 - Wright

Variables in reviewVariables in review

Semantics – abstract place to hold informationBe aware of the realities/limitations of the implementation:– Be aware of the realities/limitations of the implementation:

type, scope, and precision.

Syntax – variables need a type and an identifier– Identifier characters (a-z, A-Z, 0-9, , $)Identifier characters (a z, A Z, 0 9, _, $)– Leading character must not be a digit– Case sensitive

StyleStyle– Naming conventions

numOfStudents Vs. num, n, students, loopCheckValue, tempIntNUM_OF_STUDENTS (for unchanging constant/“final” values)

– Declaration conventionsDeclaration blockJust in Time

Initialization conventions

12Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

– Initialization conventions

Page 13: CS 241 CS 241 - Wright

VariablesVariables

Variable declarationint value;

Assignment statementvalue = 5;

Initialized declarationint value = 5;; ;

0x000

;

0x001

0x002

0x003

5

This is a String literal. It will be printed as is.

0x003

System.out.print("The value is ");

System.out.println(value); The integer 5 willbe printed out here.

13Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Notice no quote marks

Page 14: CS 241 CS 241 - Wright

Data types in ReviewData types in Review

Select data types with care!– int, double, boolean, and char most frequent

What about?int x = 2.0/3;

, , , qBe wary of compiler assumptions! In Java:– integer literals are cast as int

real number literals are cast as double

found : doublerequired: int

int x = 2.0/3;1 errorBUILD FAILED (t t l ti– real number literals are cast as double

– results of mixed types are promoted– Example: 2/3 is cast int 0

BUILD FAILED (total time: 0 seconds)

– Example: 2.0/3 is cast double 0.666Java automatically promotes lower precision types to higher precision types but not visa-versa!

What about?float x = 2.0/3;

found : doublei d fl

– byte -> short -> int -> long -> float -> doubleThe rules can be overridden by explict typecasting

float x = (float) (5/3.0) ;

required: floatfloat x = 2.0/3;

1 errorBUILD FAILED (total time: 0 seconds)

14Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

float x (float) (5/3.0) ;

Page 15: CS 241 CS 241 - Wright

Semantics of MethodsSemantics of Methods

Smaller, simpler, subcomponent of programProvides abstractionProvides abstraction– hide low-level details– give high-level structure to program, easier to understand overall program

flowflow– enables separable, independent development of modules as single

components that can be later used to build more complex componentsMethod have a signatureMethod have a signature– methods have a name (by convention, only one method named “main”)– zero or multiple arguments passed in as typed parameters– single result returnedsingle result returned

voidPrimitive data type or Derived data type (class/object)

In other languages, called functions, procedures, subroutines, ...

15Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Page 16: CS 241 CS 241 - Wright

Calling a Calling a valuevalue--returning methodreturning method

total = sum(value1, value2);40

20

public static int sum(int num1, int num2) {int result;result = num1 + num2;return result;

} // end method sum60

At thi i t h ld b f ili ith bli t ti th d th tAt this point, you should be familiar with public static methods that return primitive data types.

Later: other accesses modifiers (public, protected, private)

16Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Later: static Vs. regular (non-static) methods

Page 17: CS 241 CS 241 - Wright

Methods and your dataMethods and your data

A local variable is declared inside a method and is not accessible to statements outside the method. – Scope– Different methods can have local variables with the same names

because the methods cannot see each other’s local variables. – A method’s local variables exist only while the method is executing.

The values/arguments passed to the parameters of the method are copid and become local variables to that method.– Call by value– Changes to the local copies of variables do not change the original– Use returned value to make changes to primitive data types

If a reference to an object is passed to an method, then the method makes a copy of the reference and can use that reference to make changes to the actual object.

C ll b f

17Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

– Call by reference

Page 18: CS 241 CS 241 - Wright

printfprintf: formatting console output: formatting console output

system.out.printf( format, v1, v2, .. vn) Flags Meaning- Left justified

Format string:%[flags][width][.precision]type

j+ prefix with +/-0 pad with zeros, separate by thousands( negatives in parens

System.out.printf(“UID=%d\n”, uid);System.out.printf(“UID=%d\tlogin=%s\n”,

uid, loginName);

( negatives in parens

Type Meaning%d integer (digits)

printf(“%+-5d %+5d”, 10, -20)

+1 0 _ _ _ _ _ - 2 0

%f floating point%e exponential /scientific

notation (floatingpoint)%b boolean

printf(“%8.3f, %7.2f”, 1.234567, 1.234567)

%b boolean%c character%s string

18Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

_ _ _ 1 . 2 3 4 _ _ _ 1 . 2 3

Page 19: CS 241 CS 241 - Wright

Scanner: console inputScanner: console input

import java.util.Scanner; public class Main {

public static int getValue (String prompt) {Scanner keyboard = new Scanner(System.in);int userValue;System out println(prompt);System.out.println(prompt);userValue = keyboard.nextInt();return userValue;

} // end method getValue

public static void main(String [] args){int inputValue = getValue("Enter integer value: ");System.out.println("Value is ", inputValue);

} // end method main} // end method main

} // end class GetValue

19Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Page 20: CS 241 CS 241 - Wright

Scanner: File inputScanner: File input

import java.io.File;import java.util.Scanner;public class Main {

public static void main (String[] args) throws Exception {String filename = "Data.txt"; // uses working directoryil fil dl il (fil )File fileHandle = new File(filename);Scanner inputFile = new Scanner (fileHandle);

String line;String line;while ( inputFile.hasNextLine() ) {

line = inputFile.nextLine();System.out.println(line);

}inputFile.close();

} // end method main} // d l M i

20Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

} // end class Main

Page 21: CS 241 CS 241 - Wright

PrintWriterPrintWriter: File Output: File Output

import java.io.FileWriter;import java.io.PrintWriter;public class Main {

public static void main (String[] args) throws Exception {final boolean APPEND_EXISTING_FILE = true;fi l b l f lfinal boolean CLOBBER_EXISTING_FILE = false;String filename = "Data.txt"; // uses working directoryString filename2 = "C:\\Documents and Settings" +

"\\w001ted\\Desktop\\Data.txt ";\\w001ted\\Desktop\\Data.txt ;FileWriter fileHandle =

new FileWriter(filename,CLOBBER_EXISTING_FILE);PrintWriter outputFile = new PrintWriter(fileHandle);outputFile.println("Hello file!");outputFile.close();

} // end method main} // d l M i

21Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

} // end class Main

Page 22: CS 241 CS 241 - Wright

ArraysArrays

public static void main(String[] args) {int[][] numList;int[] xList = {1,2,3,4},

yList = {9, 8};numList = new int[3][];

public static void printList (int[] list) {for (int i=0; i < list.length; i++) {

System.out.print (list[i] + " ");}System out println();

numList[0] = xList;numList[1] = yList;xList = yList;

System.out.println();} // end method printList

printList (numList[0]);printList (numList[1]);printList (xList);printList (yList);

1 2 3 49 89 89 8printList (yList);

printList (numList[2]); } // end method main

9 8NullPointerException

22Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Page 23: CS 241 CS 241 - Wright

for / forfor / for--each loopseach loops

Some of the brightest people in Computer Science suggest that arrays should never be accessed randomly but only sequentiallyshould never be accessed randomly but only sequentially– Random accesses in arrays tend to be undisciplined, error prone, and

hard to prove correct.They suggest other (more advanced) data structures for random– They suggest other (more advanced) data structures for random access

The enchanced for loop (a type of for-each loop) provides a means to implement this stylistic constraintimplement this stylistic constraint.for (datatype elementVariable : collection){ statements;}

Compare:

double[] numberList = new double[20];…

for( double number : numberList) {System.out.println(number);

double[] numberList = new double[20];…for(int i=0; i< numberList.length; i++) {

System out println(numberList[i]);

23Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

y p ( );}

System.out.println(numberList[i]);}

Page 24: CS 241 CS 241 - Wright

ArrayListsArrayLists

The ArrayList class in the Java API is similar to an array, but it does not store primitive data types as elements. – ArrayList data structures store any object using a generic data type– An ArrayList can hold objects of different types!

ArrayList datastructures provide the following abstractions/features:ArrayList datastructures provide the following abstractions/features:– Add an element: The ArrayList object automatically expands as

items are added to itRemove an element: The ArrayList object automatically reduces as– Remove an element: The ArrayList object automatically reduces as items are removed from it

import java.util.ArrayList; //…ArrayList nameList = new ArrayList(); // NOTE NO SIZEArrayList nameList new ArrayList(); // NOTE NO SIZEnameList.add( new String( “Bob” ) ); // ADDING OBJECTSnameList.add( new String( “Pat” ) );nameList.add( new String (“April”) );

24Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

String name = (String) nameList.get( 0 ); // NOTE TYPECASTING!

Page 25: CS 241 CS 241 - Wright

ArrayListArrayList methodsmethods

Useful ArrayList methods:size() returns the size of the ArrayList– .size() returns the size of the ArrayList

– .add( object ) adds the object reference to the end– .add( index, object ) inserts the object before the index (updates others)– .set( index, object ) overwrites an existing object– .get ( index ) returns the object reference, but doesn’t remove it– .remove ( index) returns the object reference and removes it

ArrayList can be used as a parameterized classArrayList<String> nameList = new ArrayList<String>();

Parameterized ArrayLists can only hold objects of the named type andParameterized ArrayLists can only hold objects of the named type and returns/gets are automatically typed– Strongly typed data structures help reduce errors!

25Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Page 26: CS 241 CS 241 - Wright

The Random classThe Random class

Useful methodsnextInt ( int n) : returns an integer number [0 n)– .nextInt ( int n) : returns an integer number [0, n)

– .nextDouble() : returns a double [0.0, 1.0]– .nextInt() : returns a integer [minInt, maxInt]

import java.util.Random

…Random randomNumbers = new Random();int dieRoll randomNumbers nextInt(6)+ 1;int dieRoll = randomNumbers.nextInt(6)+ 1;…

26Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Page 27: CS 241 CS 241 - Wright

Complete Java Order of PrecedenceComplete Java Order of Precedence

Order Operator Operation Associates

0 ( ) parenthesis L to R

1 [] . , ++ --

array subscript, member selection, comma delimiter, post increment, post decrement L to R

2 ++ -- + - ! prefix increment, prefix decrement, positive, negative, NOT R to L3 (type) new type cast, object instantiation R to L4 * / % multiplication division modulo L to R4 * / % multiplication, division, modulo L to R5 + - + addition, subtraction, string concatenation L to R6 << >> >>> left shift, right shift, unsigned right shift

7 >= <= > <instanceof

greaterThanOrEqual, lessThanOrEqual, greaterThan, lessThan, type comparision L to R

8 == != equalTo, notEqualTo L to R9 & Bitwise AND, boolean AND (no short circuit) L to R10 ^ Bitwise XOR, boolean XOR (no short circuit) L to R11 | Bitwise Or, boolean OR (no short circuit) L to R12 && logical AND (short circuits) L to R12 && logical AND (short circuits) L to R 13 | | logical OR (short circuits) L to R 14 ?: Conditional operator (boolean)?(do if true):(do if false) R to L

15 =, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, ^=, |=

assignment, plusAssgn, minusAssgn, timesAssgn, dividesAssgn, moduloAssgn, leftShiftAssgn, rightShiftAssgn, rightShiftAssgnUnsigned, ANDA XORA ORA

R to L

27Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

, , , , | ANDAssgn, XORAssgn, ORAssgn

Page 28: CS 241 CS 241 - Wright

Example: Guessing gameExample: Guessing game

Guess a number gameComputer generates a random number between 1 16– Computer generates a random number between 1-16

– You guess a number– Program responds with one of three responses

Y i hi h!Your guess is too high!Your guess is too low!Your guess is correct!

You get four guesses– You get four guesses. – If your forth guess is wrong, then you loose!

Math note: What percentage of the time do you expect to win?

Example 2: draw a random card from a standard 52 card deck?

28Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

p