Docsity

Why Study Computer Science/Programming: Java & Comp. Programming II at Wright State Univ. , Study notes of Computer Science

Toggle sidebar
bg1
1
CS 241 CS 241 –– Computer Programming IIComputer Programming II
1
Wright State University, College of Engineering
Dr. T. Doom, Computer Science & Engineering CS 241
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
“Introduction to computing and programming with Java”, and Barnes’s “Objects First with Java”.
Programming basicsProgramming basics
(review)(review)
Computer programming
Semantics, syntax, and style
Variables and data type
Methods and decomposition
Methods for I/O in Java
Am I in the right place?Am I in the right place?
zWhat is computer programming?
zWhat is computer science?
zWhy 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 21
s
t
century
3
Wright State University, College of Engineering
Dr. T. Doom, Computer Science & Engineering CS 241
Computer Programming II
–
The
renaissance
man
knowledge
-
base
of
the
21
century
– Computing jobs rated among highest paying and most satisfying
zLots 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
constantly new opportunities to make new, significant contributions
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Why Study Computer Science/Programming: Java & Comp. Programming II at Wright State Univ. and more Study notes Computer Science in PDF only on Docsity!

CS 241CS 241 –– Computer Programming IIComputer Programming II

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 1

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 “Introduction to computing and programming with Java”, and Barnes’s “Objects First with Java”.

Programming basicsProgramming basics

(review)(review)

Computer programming Semantics, syntax, and style Variables and data type Methods and decomposition Methods for I/O in Java

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

z What is computer programming?

z What is computer science?

z 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

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 3

  • The renaissance man knowledge-base of the 21 century
  • Computing jobs rated among highest paying and most satisfying z 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

constantly new opportunities to make new, significant contributions

CS 241: The big pictureCS 241: The big picture

z Prior to this class you should have learned how to:

  • create an executable program ( semantics , syntax , and style )
  • 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
  • manage simple collections of data ( arrays and ArrayLists)

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 4

g p ( y y )

  • handle basic console and file I/O tasks

z 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!)
  • create, test, debug, and manage applications of moderate complexity
  • to use more sophisticated library objects and interfaces z Including libraries to manage events, threads, and graphics

Computer programmingComputer programming

z Essentially, computers are

simple devices that:

  • allow input to memory
  • allow output from memory
  • allow limited processing

(instructions) on memory

Memory

Processing Unit Input (^) Output

MAR MDR

ALU TEMP Control Unit PC IR

(keyboard) (^) (monitor)

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 5

z Computer programming is the

task of sequencing the limited

processing operations towards

solving a specific design goal.

z High level languages allow us

to specify tasks without being

aware of the specific

instructions need on a system.

Computer A

Compiler

Computer A

OS

source code

input from user output to user display inputs from files/network/etc

output to files/networks/etc

executable program

syntax errors warnings

run time

compile time

Compilation Vs. InterpretationCompilation Vs. Interpretation

z An alternative to compiling your program is to interpret your program

  • each line of your program is translated into a machine language and

Computer A

source code Compiler input from user output to user display inputs from files/network/etc

output to files/networks/etc

syntax errors warnings

interpretation

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 6

each line of your program is translated into a machine language and

immediately executed

z Like 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

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

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

z Put a class in a source file

A d fil ( ith j t i ) h ld l d fi iti

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 10

  • 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)
  • In general, each class is just a piece (unit) of the application

z Put each method in a class

  • Methods are used to perform specific tasks
  • Exactly one “main” method must exist in your source file(s)

z Put statements in each method

  • Finally, we actually get to DO something!

Control flowControl flow

z Do something z Sequential execution of statements … statement1; statement2; …

z Do something under this condition z Selection … if (condition) { statement(s); }

z Do again and again z Iteration … while (condition) { statement(s); } -or-

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 11

// a block of // statements are // treated as // one statement }

-or- if (condition) { statement(s); } else { statement(s); } …

for (initializer; condition; update expression) { statement(s); } -or- do { statement(s); } while (condition) …

Variables in reviewVariables in review

z Semantics – abstract place to hold information

  • Be aware of the realities/limitations of the implementation: z type, scope, and precision. z Syntax – variables need a type and an identifier
  • Identifier characters (a-z, A-Z, 0-9, _, $)
  • Leading character must not be a digit

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 12

  • Case sensitive z Style
  • Naming conventions z numOfStudents Vs. num, n, students, loopCheckValue, tempInt z NUM_OF_STUDENTS (for unchanging constant/“final” values)
  • Declaration conventions z Declaration block z Just in Time
  • Initialization conventions

VariablesVariables

Variable declaration

int value;

Assignment statement

value = 5;

0x 0x 0 002

Initialized declaration

int value = 5;

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 13

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

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

The integer 5 will

be printed out here.

Notice no quote marks

0 x 0x

Data types in ReviewData types in Review

z Select data types with care!

  • int, double, boolean, and char most frequent

z Be wary of compiler assumptions! In Java:

  • integer literals are cast as int
  • real number literals are cast as double
  • results of mixed types are promoted

What about? int x = 2.0/3;

found : double required: int int x = 2.0/3; 1 error BUILD FAILED (total time: 0 seconds)

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 14

yp p

  • Example: 2/3 is cast int 0
  • Example: 2.0/3 is cast double 0.

z Java automatically promotes lower precision types

to higher precision types but not visa-versa!

  • byte -> short -> int -> long -> float -> double

z The rules can be overridden by explict typecasting

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

What about? float x = 2.0/3;

found : double required: float float x = 2.0/3; 1 error BUILD FAILED (total time: 0 seconds)

Semantics of MethodsSemantics of Methods

z Smaller, simpler, subcomponent of program

z Provides abstraction

  • hide low-level details
  • give high-level structure to program, easier to understand overall program flow
  • enables separable, independent development of modules as single h b l d b ild l

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 15

components that can be later used to build more complex components

z Method 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 returned z void z Primitive data type or Derived data type (class/object)

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

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); userValue = keyboard.nextInt(); return userValue;

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 19

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 class GetValue

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 directory File fileHandle = new File(filename); Scanner inputFile = new Scanner (fileHandle);

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 20

String line; while ( inputFile.hasNextLine() ) { line = inputFile.nextLine(); System.out.println(line); } inputFile.close(); } // end method main } // end class Main

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; final boolean CLOBBER_EXISTING_FILE = false; String filename = "Data.txt"; // uses working directory

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 21

String filename2 = "C:\Documents and Settings" + "\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 } // end class Main

ArraysArrays

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

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

public static void printList (int[] list) { for (int i=0; i < list.length; i++) { System.out.print (list[i] + " "); } System.out.println(); } // end method printList

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 22

xList = yList;

printList (numList[0]); printList (numList[1]); printList (xList); printList (yList); printList (numList[2]); } // end method main

NullPointerException

for / forfor / for--each loopseach loops

z Some of the brightest people in Computer Science suggest that arrays

should 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

access

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 23

z The enchanced for loop (a type of for-each loop) provides a means to

implement this stylistic constraint.

for (datatype elementVariable : collection){ statements;}

z 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]); }

ArrayListsArrayLists

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

z ArrayList datastructures provide the following abstractions/features:

  • Add an element: The ArrayList object automatically expands as

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 24

items are added to it

  • Remove an element: The ArrayList object automatically reduces as

items are removed from it

import java.util.ArrayList; //… ArrayList nameList = new ArrayList(); // NOTE NO SIZE nameList.add( new String( “Bob” ) ); // ADDING OBJECTS nameList.add( new String( “Pat” ) ); nameList.add( new String (“April”) ); String name = (String) nameList.get( 0 ); // NOTE TYPECASTING!

Example: Guessing gameExample: Guessing game

z Guess a number game

  • Computer generates a random number between 1-
  • You guess a number
  • Program responds with one of three responses z Your guess is too high! z Your guess is too low!

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering CS 241Computer Programming II 28

z Your guess is correct!

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

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

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