Java Classes: Random, Character A C S L E C T U R E 6

Similar documents
Building Java Programs

Chapter 4 Classes in the Java Class Libraries

Building Java Programs

Programming with Java

Repetition, Looping. While Loop

-Alfred North Whitehead. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

Oct Decision Structures cont d

Fundamentals of Programming Data Types & Methods

Faculty of Science Midterm. COMP-202B - Introduction to Computing I (Winter 2008)

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 11, Name: KEY

Midterm Examination (MTA)

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

Java Classes: Math, Integer A C S L E C T U R E 8

Loops. CSE 114, Computer Science 1 Stony Brook University

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

The keyword list thus far: The Random class. Generating "Random" Numbers. Topic 16

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

COMP 110 Programming Exercise: Simulation of the Game of Craps

Computational Expression

Topic 16. battle -they are strictly limited in number, they require fresh horses, and must only be made at decisive moments." -Alfred North Whitehead

Full file at

Object Oriented Programming. Java-Lecture 6 - Arrays

Tutorial 12. Exercise 1: Exercise 2: CSC111 Computer Programming I

CSC Algorithms and Data Structures I. Midterm Examination February 25, Name:

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

LAB 13: ARRAYS (ONE DIMINSION)

ITERATION WEEK 4: EXMAPLES IN CLASS

CS111: PROGRAMMING LANGUAGE II

Java Coding 3. Over & over again!

Question: Total Points: Score:

H212 Introduction to Software Systems Honors

Building Java Programs Chapter 5

CompSci 125 Lecture 11

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Chapter 2. Elementary Programming

Handout 4 Conditionals. Boolean Expressions.

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.


The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Computer Science 145

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Section 2.2 Your First Program in Java: Printing a Line of Text

Condi(onals and Loops

Chapter 4: Conditionals and Recursion

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Over and Over Again GEEN163

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

CS110 Programming Language I. Lab 6: Multiple branching Mechanisms

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

CSE 114 Computer Science I

Example Program. public class ComputeArea {

private static final char[] Alphabet = "abcdefghijklmnopqrstuvwxyz".tochararray();

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

COMP 202 Java in one week

Following is the general form of a typical decision making structure found in most of the programming languages:

1. An operation in which an overall value is computed incrementally, often using a loop.

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

H212 Introduction to Software Systems Honors

1 Short Answer (10 Points Each)

Chapter 4: Control Structures I

Controls Structure for Repetition

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

FLOW CONTROL. Author: Boaz Kantor The Interdisciplinary Center, Herzliya Introduction to Computer Science Winter Semester

COMP 202. Java in one week

Control Structures: if and while A C S L E C T U R E 4

1 Short Answer (15 Points Each)

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Computer Science 145 Midterm 1 Fall 2016

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen

SFWR ENG/COMP SCI 2S03 Principles of Programming SOLUTIONS

Important Java terminology

Write a program which converts all lowercase letter in a sentence to uppercase.

Example: Monte Carlo Simulation 1

AP Computer Science A

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

Midterm Practice Problems

AP Computer Science Unit 1. Programs

ing execution. That way, new results can be computed each time the Class The Scanner

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Problem Solving With Loops

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) Midterm Examination

Repetition. Chapter 6

Repetition. Chapter 6

Conditional Execution

Midterm Practice Problems - answer key Answers appear in boldface.

CSC 1351: Quiz 6: Sort and Search

Arrays. Eng. Mohammed Abdualal

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Transcription:

Java Classes: Random, Character A C S - 1903 L E C T U R E 6

Random An instance of the Random can be used to generate a stream of random values Typical process: 1. Create a Random object 2. Use the object to get random values. Use one of: nextint() returns a random integer nextint(max) returns an integer random value in [0, max) nextdouble() returns a random value in [0.0, 1.0) nextboolean() returns a random value from {true, false Note: need an import statement import java.util.random;

Example 1 Display a random Rock-Paper-Scissors // three outcomes, all equally likely Random rand = new Random(); // nextint(3) produces a value from {0, 1, 2 switch(rand.nextint(3)) { case 0: System.out.println("Rock"); break; case 1: System.out.println("Paper"); break; case 2: System.out.println("Scissors"); break;

Example 2 Random coin toss with integer: // two-sided coin: heads/tails Random rand = new Random(); // nextint(2) produces values from {0, 1 switch(rand.nextint(2)) { case 0: System.out.println("Heads"); break; case 1: System.out.println("Tails"); break;

Example 3 Random coin toss with boolean: // two-sided coin: heads/tails Random rand = new Random(); // nextboolean() produces values from {true, false // cannot switch on booleans use if-else if(rand.nextboolean()) System.out.println("Heads"); else System.out.println("Tails");

Example 4 Simulate tossing a coin 100 times public class TossCoin { public static void main (String [] args){ int heads = 0; // counter for heads System.out.print("\ n100 tosses : "); Random g = new Random () ; for (int i=0; i<100; i++) if(g.nextboolean()) heads++; System.out.println("\ nheads : " +heads+ "\ ntails : " +(100 - heads)); TossCoin.java

Character class An instance of the Character class is not required. Character contains many useful utility methods

Example 1 Detecting letters, digits: a line of text is examined, character-by-character, to determine the character s type where type is one of {letter, digit, other Character methods used: isletter( ) returns true if the character is a letter isdigit( ) returns true if the character is a digit No instance of Character is used which means the methods are called using statements of the form if (Character.isDigit(c)) System.out.println( Prefix Character is needed to reference a static method of the Character class The argument passed to isdigit is the character c The method to execute is isdigit

Example 1 CharacterTypes.java Scanner kb = new Scanner(System.in); System.out.print("Enter a line: "); String line = kb.nextline(); // characters are examined one-by-one for (int i = 0; i < line.length(); i++){ char c = line.charat(i); if(character.isletter(c)) System.out.println(i+"\t"+c+"\t\tletter"); else if(character.isdigit(c)) System.out.println(i+"\t"+c+"\t\tdigit"); else System.out.println(i+"\t"+c+"\t\tother");

Example 2 Getting a numeric value of a character that is a digit: A line of text is examined, character-by-character, and the sum of the numeric characters is calculated Character methods used: getnumericvalue( ) returns the int value the character represents isdigit( ) returns true if the character is a digit No instance of Character is used which means the methods are called using statements of the form sum += Character.getNumericValue(c) ; The argument passed to getnumericvalue is c The Character class The method to execute is getnumericvalue

Example 2 Scanner kb = new Scanner(System.in); System.out.print("\nEnter a line: "); String line = kb.nextline(); int sum = 0; // characters are examined one-by-one for (int i = 0; i < line.length(); i++){ char c = line.charat(i); if(character.isdigit(c)){ sum += Character.getNumericValue(c); System.out.println("sum = \t"+sum); SumNumericValues.java

Example 3 Checking a control number for validity Suppose all characters must be numeric: A student number, stored as a character string, is examined character-by-character to determine if all characters are digits. Character methods used: isdigit( ) returns true if the character is a digit No instance of Character is used which means the methods are called using statements of the form if (!Character.isDigit(c)) valid = false; The Character class The argument passed to isdigit is c The method to execute is isdigit

Example 3 Scanner kb = new Scanner(System.in); System.out.println("Enter a number: "); String number = kb.next(); // characters are examined one-by-one boolean valid = true; for (int i = 0; i < number.length(); i++){ char c = number.charat(i); if(!character.isdigit(c)) valid = false; if (valid) System.out.println("Valid"); else System.out.println("Invalid"); ValidateStudentNumber.java