SNU IDB Lab. 1 Great Ideas of CS with Java Part 1 WWW & Computer programming in the language Java Ch 1: The World Wide Web Ch 2: Watch out: Here comes.

Slides:



Advertisements
Similar presentations
Computer Programming w/ Eng. Applications
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Computer Science 1620 Loops.
First project Create a JApplet with 3 textfields (2 for input and one for the answer), appropriate labels, and buttons for plus, minus and times. Your.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
8 November Forms and JavaScript. Types of Inputs Radio Buttons (select one of a list) Checkbox (select as many as wanted) Text inputs (user types text)
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 2 Data Types, Declarations, and Displays
Chapter 1 Program Design
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Computer Science 101 Introduction to Programming.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CIS Computer Programming Logic
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Introduction to Computer Systems and the Java Programming Language.
CompSci Today’s topics Java Review Just a bunch of headings meant to trigger questions A contraction of previous notes Upcoming Midterm Exam Reading.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 9 Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java Structure import java_packages; class JavaClass { member variables declarations; void otherMethod( ) { } public static void main(String[]
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 5 Arrays.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
Property of Jack Wilson, Cerritos College1 CIS Computer Programming Logic Programming Concepts Overview prepared by Jack Wilson Cerritos College.
Elements of a Java Program Bina Ramamurthy SUNY at Buffalo.
2/13/2003CSCI 150: Introduction to Computer Science1 Introduction to Computer Science CSCI 150 Section 002 Session 9 Dr. Richard J. Bonneau IONA Technologies.
Term 2, 2011 Week 1. CONTENTS Problem-solving methodology Programming and scripting languages – Programming languages Programming languages – Scripting.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Visual Basic Programming
Introduction to Java Java Translation Program Structure
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Copyright Curt Hill Variables What are they? Why do we need them?
SNU OOPSLA Lab. 1 Great Ideas of CS with Java Part 1 WWW & Computer programming in the language Java Ch 1: The World Wide Web Ch 2: Watch out: Here comes.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
Lecture 3 Introduction to Computer Programming CUIT A.M. Gamundani Presentation Layout from Lecture 1 Background.
SNU OOPSLA Lab. 1 Great Ideas of CS with Java Part 1 WWW & Computer programming in the language Java Ch 1: The World Wide Web Ch 2: Watch out: Here comes.
CompSci Today’s topics Java Numbers Iteration Upcoming More Java Reading Great Ideas, Chapter 3.
CompSci Today’s topics Java Writing Functions/Methods Upcoming Information Retrieval Reading Great Ideas, Chapter 4.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
Today’s topics Java Input More Syntax Upcoming Decision Trees More formal treatment of grammers Reading Great Ideas, Chapter 2.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
Today’s topics Java Looping Upcoming Arrays in Java Reading Great Ideas, Chapter 3.
Chapter 7 Continued Arrays & Strings. Arrays of Structures Arrays can contain structures as well as simple data types. Let’s look at an example of this,
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
CompSci Today’s topics Java Recursion Upcoming Graphics Reading Great Ideas, Chapter 4 (begin Chapter 5 for graphics)
CS 1428 Final Exam Review. Exam Format 200 Total Points – 60 Points Writing Programs – 45 Points Tracing Algorithms and determining results – 20 Points.
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
Chapter VII: Arrays.
CprE 185: Intro to Problem Solving (using C)
Today’s topics Java Arrays Upcoming Functions Reading
Approximations and Round-Off Errors Chapter 3
Chap 2. Identifiers, Keywords, and Types
Looping and Repetition
Presentation transcript:

SNU IDB Lab. 1 Great Ideas of CS with Java Part 1 WWW & Computer programming in the language Java Ch 1: The World Wide Web Ch 2: Watch out: Here comes Java Ch 3: Numerical computation & Function Ch 4: Subroutines & Databases Ch 5: Graphics Ch 6: Simulation Ch 7: Software engineering Part 2 Understanding what a computer is and how it works Ch 8: Machine architecture Ch 9: Language translation Ch 10: Virtual Environment for Computing Ch 11: Security, Privacy, and Wishful thinking Ch 12: Computer Communication Part 3 Advanced topics Ch 13: Program Execution Time Ch 14: Parallel Computation Ch 15: Noncomputability Ch 16: Artificial intelligence

SNU IDB Lab. 2 Ch 3. Numerical Computation and the Study of Functions Copyright © SNU IDB Lab.

SNU IDB Lab. 3 Table of contents Let’s Calculate Some Numbers Some Simple Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary

SNU IDB Lab. 4 Number crunching example Many situations like below Yearly bank interest rate: 5% & Your asset: $10000 You want to know how much you would earn after 20 years? Two obvious solutions Do it yourself using a calculator 20 times Write a program and let a machine find the answer. Solving optimization problems Find the best value for a parameter in some situation

SNU IDB Lab. 5 Figure 3.1 1,000 square cm of tin: How to make a largest possible cylindrical can? Solving optimization problems: Find the best value for a parameter in some situation Number crunching example

SNU IDB Lab. 6 Basic Java Facts: Variables and Data Types An object stores its state in variables (data member) Definition: A variable is an item of data named by an identifiervariable Variable declaration  To give a variable a type and a name type variable-name (ex. Int varx) The Java programming language has two categories of data types: primitive and reference. reference A variable of primitive type contains a single value of the appropriate size and format for its type a number, a character, or a boolean value. For example an integer value is 32 bits of data in a format known as two's complement the value of a character is 16 bits of data formatted as a Unicode character

SNU IDB Lab. 7 Primitive Data Types in Java

SNU IDB Lab. 8 Basic Java Fact: Primitive Data Types You can put a literal primitive value directly in your code. For example int anInt = 4; A series of digits with no decimal point is typed as an integer You can specify a long integer by putting an 'L' or 'l' after the number 'L' is preferred as it cannot be confused with the digit '1 ‘ : (ex) 8864L A series of digits with a decimal point is of type float You can specify a float by putting an 'f' or 'F' after the number: (ex) 87.14F A literal character value is any single Unicode character between single quote marks (ex) ‘greeting’ The two boolean literals  true and false

SNU IDB Lab. 9 Basic Java Fact: Reference Data Types Arrays, classes, and interfaces are reference typesreference The value of a reference type variable is a reference to the value or set of values represented by the variable A reference to the value == an address of the value A reference is called a pointer, or a memory address in other languages. The Java programming language does not support the explicit use of addresses like other languages do So, there is no pointer in Java Java use the variable's name instead. Int[] SampleArray;

SNU IDB Lab. 10 Basic Java Fact: “Final” Variables You can declare a variable in any scope to be finalfinal The value of a final variable cannot change after it has been initialized Such variables are similar to constants in other programming languages To declare a final variable, use the final keyword in the variable declaration before the type: final int aFinalVar = 0; You may defer initialization of a final local variable. Declare and initialize it later, like this: final int blankfinalsample;... blankfinalsample = 0; A final local variable that has been declared but not yet initialized is called a blank final.

SNU IDB Lab. 11 Java Fact on Floating Point Data Types Limitations of “int” data type 32bit (two’s complement) Minimum and maximum of int (-2,147,483,648 ~~ 2,147,483,647) “long” data type extends the range Cannot take on fractional values like The solution is using real numbers. Real numbers are specified with floating point ( 부동소수점 ) data type In Java, there are two data types in this category (float and double) float is single-precision floating point ( 단정도 실수 ) double is double-precision floating point ( 배정도 실수 ) FP(Floating Point) data type represents numbers in two parts significant digits and an exponent 177 might be represented as 1.77 * 10 2 in float data type

SNU IDB Lab. 12 Roundoff error in floating point numbers Even if we are using “double” data type, the following things still can happen! 64 bit representation is not enough for some cases An infinite decimal expansion: …… will not fit in a computer register Instead, will be stored More than 17 digit decimal number: is approximated by the computer to There are some tricks for the above cases, but,,,,,,,,, import java.math.BigDecimal (or import.java.math.BigInteger) BigDecimal bignum = new BigDecimal(" ")

SNU IDB Lab. 13 ErrorDemo program: a program for reading a number and printing the same number (1) Import awb.*; Import java.awt.*; Import java.awt.event.*; Public class ErrorDemo extends java.applet.Applet implements ActionListener { double data, extra; DoubleField dataF, extraF; Button b1; Public void init () { dataF = new DoubleField(20); dataF.setLabel(“Data”); extraF = new DoubleField(20); extraF.setLabel(“Extra”); b1 = new Button(“Compute”); b1.addActionListener(this); add(dataF); add(extraF); dataF.setDouble(0); extraF.setDouble(0); }

SNU IDB Lab. 14 ErrorDemo program: a program for reading a number and printing the same number (2) Public void actionPerformed(ActionEvent event) { object cause = event.getSource(); if (cause = b1) { data = dataF.getDouble(); extra = extraF.getDouble(); data = data + extra; data = data – extra; dataF.setDouble(data); }

SNU IDB Lab. 15 Result of the ErrorDemo program (p Table 3.1) data(Input)extra(Input)data(Output)

SNU IDB Lab. 16 Table of contents Let’s Calculate Some Numbers Some Simple Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary

SNU IDB Lab. 17 Two Special Classes for easy-handling Numbers only for this textbook (See appendix) ** These classes enable you to read and write int and double numbers easily in applets without having to deal with additional Java syntax. ** Put these into awb directory under your public html directory and then use the import awb.* command at the top of each program public class IntField extends TextField { public IntField(); public IntField(int size); public void setInt(int number); public int getInt(); } public class DoubleField extends TextField { public DoubleField(); public DoubleField(int size); public void setDouble(double num); public double getDouble(); }

SNU IDB Lab. 18 Calculating Cylinder Volume User puts values for radius and length of a cylinder Using DoubleField in example of calculating cylinder volume CylVol.java.java

SNU IDB Lab. 19 import awb.*; import java.awt.*; import java.awt.event.*; public class Numbers extends java.applet.Applet implements ActionListener { TextField instruct, result, mRadius, mLength; DoubleField gRadius, gLength; Button bCompute; double radius, length, cylVol, pi= ; public void init () { instruct = new TextField(72); instruct.setText("Please enter radius and length below."); mRadius = new TextField(9); mRadius.setText("radius:"); mLength = new TextField(9); mLength.setText("length:"); gRadius = new DoubleField(10); gLength = new DoubleField(10); result = new TextField(72); result.setText("The volume of the cylinder is: " + cylVol); bCompute = new Button("Compute"); bCompute.addActionListener(this); add(instruct) ; add(mRadius) ; add(gRadius) ; add(mLength) ; add(gLength) ; add(bCompute) ; add(result) ; } public void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if (cause == bCompute) { length = gLength.getDouble(); radius = gRadius.getDouble(); cylVol = pi * radius * radius * length; result.setText("The volume of the cylinder is: " + cylVol); } CylVol.java

SNU IDB Lab. 20 Installment-based Purchase Calculation Suppose you are going to buy a car on the installment plan You want to know monthly payments by clicking a button Variables: principal, rate, payment, balance ButCompound.java Iteration by Button Pushing Often need to repeat a calculation with minor changes Sometimes refine previous solution Sometimes calculate successive values in series Can do this under control of a button

SNU IDB Lab. 21 import awb.*; import java.awt.*; import java.awt.event.*; public class ButCompound extends java.applet.Applet implements ActionListener { TextField mInstruct, mBalance; DoubleField gRate, gPrinc, gPay; IntField gMonths; Button bStart, bNextInstallment; double rate, princ, pay, balance; int months; public void init() { mInstruct = new TextField(80); mInstruct.setText("Enter principal, rate, payment, " + "then press Start"); gPrinc = new DoubleField(10); gRate = new DoubleField(10); gPay = new DoubleField(10); mBalance = new TextField(80); bStart = new Button("Start"); bNextInstallment = new Button("Next Installment"); bStart.addActionListener(this); bNextInstallment.addActionListener(this); add(mInstruct); add(gPrinc); add(gRate); add(gPay); add(bStart); add(bNextInstallment); add(mBalance); } public void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if (cause == bStart) { princ = gPrinc.getDouble(); rate = gRate.getDouble()/12; pay = gPay.getDouble(); months = 0; balance = princ; mInstruct.setText("Press Next Installment for next Balance"); mBalance.setText("After " + months + " months at " + 100*rate*12 + "% and payments of " + pay + " the balance is " + balance); } if (cause == bNextInstallment) { months = months + 1; balance = balance*(1.0 + rate) - pay; mBalance.setText("After " + months + " months at " + 100*rate*12 + "% and payments of " + pay + " the balance is " + balance); } ButCompound.java

SNU IDB Lab. 22 Table of contents Let’s calculate some numbers Some Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary

SNU IDB Lab. 23 Java Control Flow Statements

SNU IDB Lab. 24 The Looping statements You use a while or do-while or for statement to continually execute a block of statements while a condition remains true.while The general syntax of the while statement is: while (expression) { statement(s) } Example: int sum = 0; int k = 0; while (k < 100) { k = k + 1; sum = sum + k; }

SNU IDB Lab. 25 The Looping Statements The general syntax of the do - while : do { statement(s) } while (expression); The for statement provides a compact way to iterate over a range of values. The general form of the for statement: for (initialization; termination; increment) { statement(s) }

SNU IDB Lab. 26 Searching the best value: CylinderVolumeMax Figure 3.1 1,000 square cm of tin: How to make a largest possible cylindrical can?  Find such radius  Find such volume

SNU IDB Lab. 27 Searching the best value: CylinderVolumeMax Volume V = Pi * r * r * h Area A = 2 * Pi * r * r + 2 * Pi * r * h = 1000 If we remove h from V V = 500 * r - Pi * r * r * r Start with r =1 cm Keep going by increasing r by 1 until V becomes maximum

SNU IDB Lab. 28 Figure 3.4

SNU IDB Lab. 29 Figure 3.5

SNU IDB Lab. 30 Figure 3.6

SNU IDB Lab. 31 CylinderVolumeMax Algorithm Set r at some starting value. Decide how much r should be increased each cycle Mostly given by the user Algorithm Initialize previous V at zero. Find V. Repeat the following: (1) if V < previousV, stop loop (2) increase r by some amount (3) save V in a place called “previousV”. (4) find V After looping, Previous V is supposed to have Max Volume

SNU IDB Lab. 32 import awb.*; import java.awt.*; import java.awt.event.*; public class CylinderVolumeMax extends java.applet.Applet implements ActionListener { double r, previousV, increase, V; DoubleField rF, increaseF, VF; Button b1; public void init () { rf = new DoubleField(20); rf.setLabel( “ Radius ” ); increaseF = new DoubleField(20); increaseF.setLabel( “ increase ” ); b1 = new Button( “ Compute ” ); b1.addActionListener(20); add(rF) ; add(increaseF) ; add(b1) ; add(VF) ; rF.setDouble(1.0); increaseF.setDouble(0.01); } CylinderVolumeMax.Java

SNU IDB Lab. 33 Pubic void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if (cause == b1) { r = rF.getDouble(); increase = increaseF.getDouble(); previousV = 0; V = 500 * r – * r * r * r; while(V >= previousV) { r += increase; previousV = V; V = 500 * r – * r * r * r; } VF.setDouble(previousV); } CylinderVolumeMax.Java

SNU IDB Lab. 34 One last thing to consider in searching the best value! Local-Maxima Loophole

SNU IDB Lab. 35 Computing Interests CompInterest.java Wild Card Bonus (WCB-1)! Submit 5 page report explaining the following code Diamond.java Another Looping examples

SNU IDB Lab. 36 import awb.*; import java.awt.*; import java.awt.event.*; public class CompInterest extends java.applet.Applet implements ActionListener { TextField mInstruct, mBalance; DoubleField gRate, gPrinc, gPay; Button bCompute; IntField gMonths; double rate, princ, pay, balance; int months, k; public void init() { mInstruct = new TextField(80); mInstruct.setText("Enter principal, rate, payment, " + "#months; then press 'Compute'"); gPrinc = new DoubleField(10); gRate = new DoubleField(10); gPay = new DoubleField(10); gMonths = new IntField(10); bCompute = new Button("Compute"); mBalance = new TextField(80); bCompute.addActionListener(this); add(mInstruct); add(gPrinc); add(gRate); add(gPay); add(gMonths); add(bCompute); add(mBalance); } public void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if (cause == bCompute) { princ = gPrinc.getDouble(); rate = gRate.getDouble()/12; pay = gPay.getDouble(); months = gMonths.getInt(); balance = princ; k = 0; while (k < months) { balance = balance*(1.0 + rate) - pay; k = k + 1; } mBalance.setText("After " + months + " months at " + 100*rate*12 + "% and payments of " + pay + " the balance is " + balance); } CompInterest.java

SNU IDB Lab. 37 import java.awt.*; import java.awt.event.*; public class Diamond extends java.applet.Applet implements ActionListener { TextField tf; TextArea ta; Button bDraw; String stars = "*******************"; String spaces = " "; int k; public void init() { tf = new TextField("Hello "); ta = new TextArea(22, 20); ta.setFont(new Font("Monospaced", Font.BOLD, 12)); bDraw = new Button("Draw"); bDraw.addActionListener(this); add(tf); add(bDraw); add(ta); } public void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if (cause == bDraw) { tf.setText("Goodbye"); k = 0; while (k < 10) { ta.append(spaces.substring(0,10-k) + stars.substring(0,2*k+1)+"\n"); k = k + 1; } k = 1; while (k < 10) { ta.append(spaces.substring(0,1+k) + stars.substring(0,19-2*k)+"\n"); k = k + 1; } Diamond.java

SNU IDB Lab. 38 Table of contents Let’s calculate some numbers Some Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary

SNU IDB Lab. 39 Concept of Array Holds multiple values of the same type Aggregate Data Types: set, bag, list Deal with items of same type The length of an array is established when the array is created (at runtime) After creation, an array is a fixed-length structure

SNU IDB Lab. 40 Motivations of Arrays Analogies mailboxes in Post Office CD rack with slots Advantages Simplifies naming of similar objects Allows use of loops Useful for statistical problems and numerical problems The most fundament data structure in computer science for constructing other advanced data structures Many other kinds of data structures are built by “Array” List Matrix Stack Queue Binary Tree And so on

SNU IDB Lab. 41 Declaring an Array in Java int[] anArray; anArray = new int[10]; = int anArray[]; anArray = new int[10]; int anArray[10]; =

SNU IDB Lab. 42 Creating and using an Array To get the size of an array, you write arrayname.length This is a member-variable. Not a function (not length() ) ! int[] anArray; // declare an array of integers anArray = new int[10];// create an array of integers // assign a value to each array element for (int i = 0; i < anArray.length; i++) { anArray[i] = i; }

SNU IDB Lab. 43 Some more on Array shortcut syntax for creating and initializing an array. boolean[] answers = { true, false, true, true, false }; int[] primeNumsBelowTen = { 2, 3, 5, 7 }; Setting up an array Declaration: double weights[ ]; Definition: weights = new double[50]; Or Combined: double weights[ ] = new double[50];

SNU IDB Lab. 44 int num[ ] = new int[6]; ?????? num[1] = 21; num[5] = 13; ?21???13 Array Creation and Use int k = 2; while(k<6) { num[k] = k*k; k = k+1; } ? ** Real Array Example Hotel.javaHotel.java: A hotel has room[500] which are all “0” in the beginning. If a guest registers a particular room P, the value of room[p] is changed to the number of guests. Whenever a new guest registers a room, the message about the room occupancy comes up.

SNU IDB Lab. 45 import awb.*; import java.awt.*; import java.awt.event.*; public class Hotel extends java.applet.Applet implements ActionListener { TextField mInstruct, mHotelCensus; IntField gRoomNo, gNoGuests; Button bRegister; int k=0, totGuests = 0, noOccupied = 0, roomNo, noGuests; int room[]; public void init() { room = new int[500]; k = 0; while (k < 500) { room[k] = 0; k = k + 1; } mInstruct = new TextField(60); mInstruct.setText("Enter room number, number of guests, "+ "then press Register"); gRoomNo = new IntField(6); gNoGuests = new IntField(6); bRegister = new Button("Register"); mHotelCensus = new TextField(60); bRegister.addActionListener(this); add(mInstruct); add(gRoomNo); add(gNoGuests); add(bRegister); add(mHotelCensus); } public void actionPerformed(ActionEvent event) { Object cause = event.getSource(); if (cause == bRegister) { roomNo = gRoomNo.getInt(); noGuests = gNoGuests.getInt(); if (room[roomNo] != 0) { mHotelCensus.setText("That room is occupied!"); } else { room[roomNo] = noGuests; totGuests = totGuests + noGuests; noOccupied = noOccupied + 1; mHotelCensus.setText("There are " + totGuests + " occupying " + noOccupied + " rooms."); } Hotel.java

SNU IDB Lab. 46 Table of contents Let’s calculate some numbers Some Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary

SNU IDB Lab. 47 Simple Statistics Program Design Algorithms for Maximum, Minimum, and Mean in the context of array Array Statistics Example ArrayStats.java Wild Card Bonus (WCB-2) Submit a 5 page report explaining ArrayStats.Java

SNU IDB Lab. 48 import awb.*; import java.awt.*; import java.awt.event.*; public class ArrayStats extends java.applet.Applet implements ActionListener { TextField mInstruct, mAnswer; IntField iCount; double list[]; Button bStore, bShow, bExtremes, bMean, bClear; int count, nextFree, nextUse; double mean(double[] list, int size) { int k = 0; double sum = 0.0; while (k < size) { sum = sum + list[k]; k = k + 1; } return sum/size; } double max(double[] list, int size) { int k = 1; double largest = list[0]; while (k < size) { if (list[k] > largest) { largest = list[k]; } k = k + 1; } return largest; } double min(double[] list, int size) { int k = 1; double smallest = list[0]; while (k < size) { if (list[k] < smallest) { smallest = list[k]; } k = k + 1; } return smallest; } public void init() { list = new double[100]; mInstruct = new TextField(70); mAnswer = new TextField(70); mInstruct.setText("Enter Value, then press Store button"); iCount = new IntField(10); bStore = new Button("Store"); bShow = new Button("Show"); bExtremes = new Button("Extremes"); bMean = new Button("Mean"); bClear = new Button("Clear"); nextFree = 0; nextUse = 0; bStore.addActionListener(this); bShow.addActionListener(this); bExtremes.addActionListener(this); bMean.addActionListener(this); bClear.addActionListener(this); add(mInstruct); add(iCount); add(bStore);

SNU IDB Lab. 49 add(bShow); add(bExtremes); add(bMean); add(bClear); add(mAnswer); } public void actionPerformed(ActionEvent event) { int value, total;; Object cause = event.getSource(); if (cause == bStore) { value = iCount.getInt(); list[nextFree] = value; nextFree = nextFree + 1; iCount.setInt(); // clear IntField } if (cause == bShow) { mAnswer.setText("The value in element "+nextUse+" is "+ list[nextUse]); nextUse = (nextUse + 1)% nextFree; } if (cause == bExtremes) { mAnswer.setText("The largest data item is " + max(list, nextFree) + " and the smallest data item is " + min(list, nextFree)); } if (cause == bMean) { mAnswer.setText("The average is " + mean(list, nextFree)); } if (cause == bClear) { nextUse = 0; nextFree = 0; mAnswer.setText("The old data has been cleared out"); } ArrayStats.java (cont’d)

SNU IDB Lab. 50 Table of contents Let’s calculate some numbers Some Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary

SNU IDB Lab. 51 Advanced discussion: Putting things in an Array The question of whether there are enough bins to hold all the elements of a set of objects If we can succeed with a set, the set is countable If countable  computable  solvable  decidable What about the set of positive numbers What about the set of positive and negative integers ?????    An unending chain of bins than extends off into infinity

SNU IDB Lab. 52 Advanced discussion: Uncomputability Let’s consider: the functions that input a positive integer and yields a positive integer cannot be put in a row No matter how one tries to squeeze them all into bins, there will always be huge numbers more that will not fit The notion of uncountable set This is an important property with great implications for computer science  uncomputability

SNU IDB Lab. 53 Figure 3.9 Let’s call the function that accept positive numbers as input and yield positive integers as output PIPO type function Let’s assume the set of PIPO type functions is countable If the assumption is true, all PIPO type functions would be put into bins successfully That means no left-overs. But …..

SNU IDB Lab. 54 Figure 3.10 ** However, Consider the new function constructed as in Figure 3.10 ** The new function is definitely different from existing functions and definitely PIPO type function ** But it was not in the bin! ** The set of PIPO type functions is uncountable! ** The notion of uncountable set leads to uncomputability! (chap 15)

SNU IDB Lab. 55 Table of contents Let’s Calculate some Numbers Some Calculations Looping and a Study of Functions Storing Information in Arrays Simple Statistics Program Design Putting Things on Array Summary

SNU IDB Lab. 56 Summary This chapter has discussed many aspects of numerical computation We covered many Java constructs through sample programs “Integers” are not adequate for general numerical computation Even “Double” data type has round-off errors Looping programs are frequent Arrays were useful Putting things into an array is simple job but can lead to a discussion of uncomputability

SNU IDB Lab. 57 Ch3: Mumerical Computation & Function Textbook Review Time