The first applet we shall build will ask the user how many times the die is to be tossed. The request is made by utilizing a JoptionPane input form:

Similar documents
Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

Arrays (Deitel chapter 7)

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Methods (Deitel chapter 6)

2.8. Decision Making: Equality and Relational Operators

Methods (Deitel chapter 6)

Chapter 3 - Introduction to Java Applets

Extra Credit Lab. Your job is to catch any syntax errors a user might make. Two examples follow. In the panel on the left the user has used

Course PJL. Arithmetic Operations

Copyright 1999 by Deitel & Associates, Inc. All Rights Reserved.

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type

Part 8 Methods. scope of declarations method overriding method overloading recursions

Chapter 6 Arrays and Strings Prentice Hall, Inc. All rights reserved.

Defining Classes and Methods

Outline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays

Chapter 6 - Methods Prentice Hall. All rights reserved.

Decisions: Logic Java Programming 2 Lesson 7

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Types and Expressions. Chapter 3

Full file at

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

The first version of the bank will look like this:

STUDENT LESSON A7 Simple I/O

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

CS 116 Week 8 Page 1

Fundamentals of Programming. Lecture 3: Introduction to C Programming

CS 231 Data Structures and Algorithms, Fall 2016

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Chapter 4 Control Structures: Part 2

Chap. 3. Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L,

Full file at

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Introduction to Java Unit 1. Using BlueJ to Write Programs

Lesson 3: Accepting User Input and Using Different Methods for Output

Eng. Mohammed S. Abdualal

Simple Java Programming Constructs 4

CS Fall Homework 5 p. 1. CS Homework 5

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

CS 335 Lecture 02 Java Programming

BCIS 3630 Dr. GUYNES SPRING 2018 TUESDAY SECTION [JAN version] GRADER COURSE WEBSITE

A variable is a name for a location in memory A variable must be declared

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

CS112 Lecture: Defining Instantiable Classes

Practice Midterm 1. Problem Points Score TOTAL 50

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Java Libraries. Lecture 6 CGS 3416 Fall September 21, 2015

Flow of Control Branching 2. Cheng, Wei COMP May 19, Title

CS 106 Introduction to Computer Science I

Fundamentals of Programming Session 14

COMP 110 Project 1 Programming Project Warm-Up Exercise

Bitwise Operators Objects and Methods

More About Objects and Methods

AP Computer Science Unit 1. Writing Programs Using BlueJ

Exam 1 - (20 points)

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1

CS 106 Introduction to Computer Science I

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Introduction to Computation and Problem Solving

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Lecture 3. Input, Output and Data Types

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Unit 1 Lesson 4. Introduction to Control Statements

Chapter 12 Advanced GUIs and Graphics

1.00 Lecture 34. Sorting 2. Reading for next time: Big Java Counting sort

Fundamentals of Programming Session 4

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Sun ONE Integrated Development Environment

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

Java Primer 1: Types, Classes and Operators

Introduction to the Java Basics: Control Flow Statements

Programming for Engineers Functions

4. Java language basics: Function. Minhaeng Lee

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Introduction to C# Applications

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

CT 229 Fundamentals of Java Syntax

Lecture 6: While Loops and the Math Class

C: How to Program. Week /Mar/05

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

infix expressions (review)

CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions

Programming with Java

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

In this lab, you will learn more about selection statements. You will get familiar to

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Graphics User Defined Forms, Part I

Chapter 4 Introduction to Control Statements

Chapter 2: Using Data

CS 139 Practice Midterm Questions #2

Adding Existing Source Code in NetBeans CS288, Autumn 2005 Lab 002

19. GUI Basics. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Transcription:

Lecture 5 In this lecture we shall discuss the technique of constructing user-defined methods in a class. The discussion will be centered about an experiment of tossing a die a specified number of times. A die is a six sided cube having 1 to 6 spots on its six edges. When an honest die is rolled, say, 240 times a "1" should appear about 1/6 of the time; that is, a "1" should come up about 40 times. The same can be said for each of the other faces. In 240 tosses each face should appear about 40 times. The first applet we shall build will ask the user how many times the die is to be tossed. The request is made by utilizing a JoptionPane input form: In this example the user typed in 24000. After the OK button the applet simulates 24000 rolls of a die and then presents summary of the results: In this experiment 3904 1s were rolled. Each face appears "about", not "exactly", 4000 times. Rolling a Die The Math method random() can be used to simulate any number of rolls of a die. The java call Math.random() produces a "random" number that is greater than or equal to 0 and strictly less than 1. Intuitively, if we called random() 1000 times we should get a thousand numbers evenly spread out in the interval [0, 1). The java command 6*Math.random() 1

will produce a random double in the range from 0 to 5.99999... The command (int) (6*Math.random()) will produce a random integer in the range from 0 to 5. This is because casting, wrapping a pair of parentheses about int, returns the integer part of the double number that follows (int). Finally 1+(int) (6*Math.random()) will return a random integer between 1 and 6. Example: Simulating Tossing a Die, An Overiew The structure of the applet to be constructed might be outlined as: The user is prompted to enter the number of rolls. Then the specified number of rolls are made and the results summarized. This is an outline of the code to be written: import java.awt.*; import javax.swing.*; public class TossDie extends JApplet public void init() setsize(200,100); Container c = getcontentpane(); JTextArea outputarea = new JTextArea(); c.add(outputarea); int M; String Tabulation; M = getnumberofrolls(); Tabulation = rolloften(m); outputarea.settext(tabulation); } // end init() public int getnumberofrolls() } // end getnumberofrolls() public int rollonce() } // end rollonce() public String rolloften(int rolls) } // rolloften(int rolls) } // end class TossDie 2

Three methods are to be constructed in this applet: public int getnumberofrolls() public int rollonce() public String rolloften(int rolls) The syntax for the first line of a method is the word public (in all three cases here and in the near future); the data type the method will return (the first two will return the type int, the third String ); the name of the method (it should be descriptive). The final pair of parentheses () in the title line is part of the name and is called the parameter list of the method. In the first two cases the parameter list is empty. In the last case the parameter list (int rolls) states what parameters(s) the method will need to carry out its' job. The parameter's type as well as its name appears; no commas separate the two. Once the methods are constructed they are strung together in the method init() to carry out the task at hand. The code setsize(200,100); Container c = getcontentpane(); JTextArea outputarea = new JTextArea(); c.add(outputarea); sets the size of the output screen and provides a text area and container for the text. Next M = getnumberofrolls(); gets the number of times the user wants to toss the die. The method rolloften(m) does two things: it rolls the die M times and summarizes the results in a string, which is captured by the string Tabulation. Tabulation = rolloften(m); The summary is printed out by means of the line: Constructing the Methods outputarea.settext(tabulation); We begin by writing getnumberofrolls(). It is built in a straightforward way, utilizing JOptionPane: public int getnumberofrolls() String numberofrolls; int m; numberofrolls = JOptionPane.showInputDialog 3

("Enter the number of rolls"); m = Integer.parseInt(numberOfRolls); return m; } // end getnumberofrolls() Note the last line of the method, return m;. The value a method returns appears in the last line of the method and is preceded by the word "return". A method need not "return" a value. If this is the case the type of the method is replaced by the word "void". The first line of the init() method public void init() is an example of such a method. We will come back to this point later. The method rollonce() simulates one toss of a die. public int rollonce() int face; face = 1 +(int)(6*math.random()); return face; }// end rollonce() The value returned here is an integer beween 1 and 6. Finally rolloften(int rolls) executes, summarizes, and returns the summary as a string: public String rolloften(int N) int face1 = 0, face2 = 0, face3 =0, face4 = 0, face5 = 0, face6 = 0; String output = ""; int result; for (int i = 1; i <= N; i++) result = rollonce(); if (result == 1) face1++; if (result == 2) face2++; if (result == 3) face3++; if (result == 4) face4++; if (result == 5) face5++; if (result == 6) face6++; } //end for output = output +" # of 1s = " + face1 + "\n"+ " # of 2s = " + face2 + "\n"+ " # of 3s = " + face3 + "\n"+ " # of 4s = " + face4 + "\n"+ " # of 5s = " + face5 + "\n"+ " # of 6s = " + face6 + "\n"; 4

return output; }// end rolloften(int rolls) As for the details of rolloften(int N), it is a method whose purpose is to returns the string named output. To go on to the details, we assign the initial values of 0 to face1 through face6 and the null value "" to the string output: int face1 = 0, face2 = 0, face3 =0, face4 = 0, face5 = 0, face6 = 0; String output = ""; If you do not assign these initial values then, at compile time, you will get an error message saying that these values need to be initialized. To continue, the for loop } //end for for (int i = 1; i <= N; i++) int result = rollonce(); if (result == 1) face1++; if (result == 2) face2++; if (result == 3) face3++; if (result == 4) face4++; if (result == 5) face5++; if (result == 6) face6++; carries out the experiment N times and keeps a record of how many times each face has been rolled. Finally, a summary is made and returned as the value of the method: output = output +" # of 1s = " + face1 + "\n"+ " # of 2s = " + face2 + "\n"+ " # of 3s = " + face3 + "\n"+ " # of 4s = " + face4 + "\n"+ " # of 5s = " + face5 + "\n"+ " # of 6s = " + face6 + "\n"; return output; The complete program is import java.awt.*; import javax.swing.*; public class TossDie extends JApplet 5

public void init() Container c = getcontentpane(); JTextArea outputarea = new JTextArea(); c.add(outputarea); int M; String Tabulation; M = getnumberofrolls(); Tabulation = rolloften(m); outputarea.settext(tabulation); } // end init() public int getnumberofrolls() String numberofrolls; int m; numberofrolls = JOptionPane.showInputDialog ("Enter the number of rolls"); m = Integer.parseInt(numberOfRolls); return m; }//end getnumberofrolls() public int rollonce() int face; face = 1 +(int)(6*math.random()); return face; }// end rollonce() public String rolloften(int N) int face1 = 0, face2 = 0, face3 =0, face4 = 0, face5 = 0, face6 = 0; String output = ""; for (int i = 1; i <= N; i++) int result = rollonce(); if (result == 1) face1++; if (result == 2) face2++; if (result == 3) face3++; if (result == 4) face4++; if (result == 5) face5++; if (result == 6) face6++; } //end for 6

output = output + " # of 1s = " + face1 + "\n"+ " # of 2s = " + face2 + "\n"+ " # of 3s = " + face3 + "\n"+ " # of 4s = " + face4 + "\n"+ " # of 5s = " + face5 + "\n"+ " # of 6s = " + face6 + "\n"; return output; }// end rolloften(int rolls) } // end class TossDie 7

Lab 3. You are to write an applet that simulates N tosses of a pair of honest, five sided dies. The program, to be called FiveSidedDie, combines the looping of Lab2 with the use of methods illustrated in today's lecture. JoptionPanes are to be used throughout the program for getting and giving information. The program is to begin by telling the user what the applet does: After the user clicks on the OK button a window requesting the integer N. In the window below the user has typed in 500: After the OK button is clicked here a summary of the expected and actual number of tosses is presented in a JOptionPane: A little bit of probability: since each face of the honest 5-sided die will appear with probability 1/5 the expected number of times of tossing a sum from 2 to 10 in N tosses may be tabulated as: sum 2 3 4 5 6 7 8 9 10 8

exptd N/25 2N/25 3N/25 4N/25 5N/25 4N/25 3N/25 2N/25 N/25 Also, use java's division of integers by integers method when presenting these expected number of tosses. (Consequently, the expected values will be correct if the N entered is a multiple of 25, but will be off by as much as 4/5 if N is not a multiple of 25) To, continue, once the user clicks the OK button in the last window he or she will be asked if they wish to try another simulation: If the integer entered is not a 0 or a 1 the program will cycle: If the user types in a 1, the program repeats by asking for N: 9

The expected column totals up to 53, not 57. This is because of java's method of integer division, mentioned earlier. The actual column does add up to 57, the total number of tosses. 10