CS1150 Principles of Computer Science Math Functions, Characters and Strings (Part II)

Similar documents
CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Chapter 4 Mathematical Functions, Characters, and Strings

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Eng. Mohammed Abdualal

Module 4: Characters, Strings, and Mathematical Functions

MATHEMATICAL FUNCTIONS CHARACTERS, AND STRINGS. INTRODUCTION IB DP Computer science Standard Level ICS3U

Chapter 12 Strings and Characters. Dr. Hikmat Jaber

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

Chapter 4 Mathematical Functions, Characters, and Strings

Chapter 4. Mathematical Functions, Characters, and Strings

Computer Programming, I. Laboratory Manual. Experiment #5. Strings & Text Files Input

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

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

"Hello" " This " + "is String " + "concatenation"

Chapter 2 Primitive Data Types and Operations. Objectives

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

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 Strings. Interned Strings. Strings Are Immutable. Variable declaration as String Object. Slide Set 9: Java Strings and Files

Chapter 8 Strings. Chapter 8 Strings

Chapter 2 ELEMENTARY PROGRAMMING

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters

Chapter 2 Elementary Programming

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

Eng. Mohammed Abdualal

Review. Single Pixel Filters. Spatial Filters. Image Processing Applications. Thresholding Posterize Histogram Equalization Negative Sepia Grayscale

Programming with Java

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

Using Java Classes Fall 2018 Margaret Reid-Miller

CS 1301 Ch 8, Part A

Getting started with Java

More on variables and methods

STUDENT LESSON A10 The String Class

Chapter 2 Primitive Data Types and Operations

Chapter 9 Strings and Text I/O

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

CST242 Strings and Characters Page 1

Creating Strings. String Length

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 2 Primitive Data Types and Operations

Class Library java.lang Package. Bok, Jong Soon

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

String related classes

Gaddis: Starting Out with Java: From Control Structures through Objects, 6/e

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

Starting Out with Java: From Control Structures through Data Structures 3e (Gaddis and Muganda) Chapter 2 Java Fundamentals

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

CS1150 Principles of Computer Science Arrays

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

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

STRINGS AND STRINGBUILDERS. Spring 2019

String. Other languages that implement strings as character arrays

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

double float char In a method: final typename variablename = expression ;

AP Computer Science A

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

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

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Chapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

- Thus there is a String class (a large class)

Full file at

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

What methods does the String class provide for ignoring case sensitive situations?

Java: Learning to Program with Robots

Honors Computer Programming 1-2. Chapter 5 Exam Prep

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Welcome to the Using Objects lab!

Programming with Java

Elementary Programming

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Oct Decision Structures cont d

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

COMP Primitive and Class Types. Yi Hong May 14, 2015

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

CS Programming I: Using Objects

USING LIBRARY CLASSES

Java Console Input/Output The Basics. CGS 3416 Spring 2018

More non-primitive types Lesson 06

Strings in Java String Methods. The only operator that can be applied to String objects is concatenation (+) for combining one or more strings.

CS 101 Exam 1 Spring 200 Id Name

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

CS1150 Principles of Computer Science Loops (Part II)

Midterm Examination (MTA)

Motivations 9/14/2010. Introducing Programming with an Example. Chapter 2 Elementary Programming. Objectives

Chapter 2 Elementary Programming

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

Announcements. CompSci 100e Program Design and Analysis II

Basic Computation. Chapter 2

CS 106 Introduction to Computer Science I

Chapter 9 Strings and Text I/O

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Full file at

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

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017

Lab 14 & 15: String Handling

4 WORKING WITH DATA TYPES AND OPERATIONS

Transcription:

CS1150 Principles of Computer Science Math Functions, Characters and Strings (Part II) Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs

How to generate a random character? Every character has a unique Unicode between 0 and FFFF in hexadecimal (65535 in decimal) o To generate a random character: generate a random integer between 0 and 65535 (inclusive) o char c = (int)(math.random() * (65535 + 1)); // char c = 97 is equivalent to char c = (char) 97 int d = (int)(math.random() * (65535 + 1)); System.out.println(d); // 44188 System.out.println((char)d); // 겜 UC. Colorado Springs

Seeing?? In Eclipse With the current window selected --> Edit --> Set Encoding --> Choose UTF-8 in Other CS4500/5500 UC. Colorado Springs

How to generate a random lower case character? The Unicodes for lowercase letters are consecutive integers starting from the Unicode for a, then that for b, c,..., and z o The Unicode for a is (int)'a o A random integer between (int)'a' and (int)'z' } (int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1)) all numeric operators can be applied to the char operands } (int)('a' + Math.random() * ('z' - 'a' + 1)) } char c = (char)( a' + Math.random() * ( z' - a' + 1)); UC. Colorado Springs

How to generate a random character? A random character between any two characters ch1 and ch2 with ch1 < ch2 can be generated as: o (char)(ch1 + Math.random() * (ch2 ch1 + 1)) o o Example: random upper case letter } (char)( A + Math.random() * ( Z A + 1)) Example: random numeric character } (char)( 0 + Math.random() * ( 9 0 + 1)) UC. Colorado Springs

How to convert a numeric int character to its int value? Converting 0 to 0, etc. Example: how to convert 0 to 0? o 0-0 is 0 o 1-0 is 1 o 2-0 is 2 o... UC. Colorado Springs

The String Type The char type only represents one character. To represent a string of characters, use the data type called String. For example, String message = "Welcome to Java"; String is a predefined class in Java just like the Math class and Character class (note all classes have names first letter capitalized). 7

The String Type A char is in single quotes and a String is in double quotes o char middleinitial = "M"; // Error - can t convert String to char o char middleinitial = 'M'; // Correct o string studentname = "Max" // Error - uppercase "String" o String studentname = 'Max'; // Error - double quotes o String studentname = "Max"; // Correct CS1150 UC. Colorado Springs

Simple Methods for String Objects Method length() charat(index) concat(s1) touppercase() tolowercase() trim() Description Returns the number of characters in this string. Returns the character at the specified index from this string. Returns a new string that concatenates this string with string s1. Returns a new string with all letters in uppercase. Returns a new string with all letters in lowercase. Returns a new string with whitespace characters trimmed on both sides. 9

Getting String Length String message = "Welcome to Java"; System.out.println("The length of " + message + " is " + message.length()); 10

Getting Characters from a String Index runs from 0 to length() minus 1. Examples: String message = "Welcome to Java"; System.out.println("The first character in message is " + message.charat(0)); System.out.println("The last character is " + message.charat(message.length()-1)); How to iterate the String through each character? 11

Converting Strings "Welcome".toLowerCase() returns a new string, welcome. "Welcome".toUpperCase() returns a new string, WELCOME. " Welcome ".trim() returns a new string, Welcome. trim(): Returns a string with all white space characters removed from front or end of string White space characters include space, tab, line feed, form feed, carriage return 12

String Concatenation String s3 = s1.concat(s2); or String s3 = s1 + s2; // Three strings are concatenated String message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2 String s = "Chapter" + 2; // s becomes Chapter2 // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s1 becomes SupplementB 13

String Concatenation Notes about + o o When only one of the operands is a String, the other will be converted into a String and concatenation occurs When neither operand is a String, then addition operation occurs Example: String1.java CS1150 UC. Colorado Springs

Reading a String from the Console next(): reads string until a white space character is reached Scanner input = new Scanner(System.in); System.out.print("Enter three words separated by spaces: "); String s1 = input.next(); String s2 = input.next(); String s3 = input.next(); System.out.println("s1 is " + s1); System.out.println("s2 is " + s2); System.out.println("s3 is " + s3); 15

Reading a String from the Console nextline(): reads string until an enter key is reached Scanner input = new Scanner(System.in); System.out.print("Enter a String: "); String s = input.nextline(); System.out.println("The String entered is " + s); 16

Reading a Character from the Console Scanner input = new Scanner(System.in); System.out.print("Enter a character: "); String s = input.nextline(); // input.next() works too char ch = s.charat(0); System.out.println("The character entered is " + ch); Shortcut: input.nextline().charat(0); 17

Comparing Strings Method equals(s1) equalsignorecase(s1) compareto(s1) comparetoignorecase(s1) startswith(prefix) endswith(suffix) Description Returns true if this string is equal to string s1. Returns true if this string is equal to string s1; it is case insensitive. Returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this string is greater than, equal to, or less than s1. Same as compareto except that the comparison is case insensitive. Returns true if this string starts with the specified prefix. Returns true if this string ends with the specified suffix. 18

Comparing Strings Attempting to compare Strings with relational operators will cause errors o Use equals() or equalsignorecase() instead of == } str1.equals(str2) // returns true or false o Use compareto() instead of <, >, <=, >= o } str1.compareto(str2) // returns an integer } > 0 if str1 is greater than str2 } = 0 if str1 is equal to str2 } < 0 if str1 is less than str2 Example: Order2Cities.java CS1150 UC. Colorado Springs

Case Study: Lottery Program Using Strings Generates a random two-digit number, then prompts the user to enter a two-digit number, and determines whether the user wins according to the following rule: 1. If the user input matches the lottery number in the exact order, the award is $10,000. 2. If all the digits in the user input match all the digits in the lottery number, the award is $3,000. 3. If one digit in the user input matches a digit in the lottery number, the award is $1,000. Lottery.java 20

Conversion between Numbers and Strings Using + o o When one of the operands is a String, the other will be converted into a String and concatenation occurs String s = 6 + ; // converts integer 6 to a string CS1150 UC. Colorado Springs

Obtaining Substrings Method substring(beginindex) substring(beginindex, endindex) Description Returns this string s substring that begins with the character at the specified beginindex and extends to the end of the string. Returns this string s substring that begins at the specified beginindex and extends to the character at index endindex 1. Note that the character at endindex is not part of the substring. 22

Finding a Character or a Substring in a String Method indexof(ch) indexof(ch, fromindex) indexof(s) indexof(s, fromindex) lastindexof(ch) lastindexof(ch, fromindex) lastindexof(s) lastindexof(s, fromindex) Description Returns the index of the first occurrence of ch in the string. Returns -1 if not matched. Returns the index of the first occurrence of ch after fromindex in the string. Returns -1 if not matched. Returns the index of the first occurrence of string s in this string. Returns -1 if not matched. Returns the index of the first occurrence of string s in this string after fromindex. Returns -1 if not matched. Returns the index of the last occurrence of ch in the string. Returns -1 if not matched. Returns the index of the last occurrence of ch before fromindex in this string. Returns -1 if not matched. Returns the index of the last occurrence of string s. Returns -1 if not matched. Returns the index of the last occurrence of string s before fromindex. Returns -1 if not matched. 23

Finding a Character or a Substring in a String int k = s.indexof(' '); String firstname = s.substring(0, k); String lastname = s.substring(k + 1); 24

Conversion between Strings and Numbers Integer.parseInt() o Converts a String into an integer. Example: String numericstring = "817"; int number = Integer.parseInt(numericString); System.out.println("Converted string " + numericstring + " into integer " + number); Double.parseDouble() o Converts a String into a double CS1150 UC. Colorado Springs

Formatting Output Use the printf statement. System.out.printf(format, items); Where format is a string that may consist of substrings and format specifiers. A format specifier specifies how an item should be displayed. An item may be a numeric value, character, boolean value, or a string. Each specifier begins with a percent sign %. Does not work with println. 26

Frequently-Used Specifiers Specifier Output Example %b a boolean value true or false %c a character 'a' %d a decimal integer 200 %f a floating-point number 45.460000 %e a number in standard scientific notation 4.556000e+01 %s a string "Java is cool" int count = 5; items double amount = 45.56; System.out.printf("count is %d and amount is %f", count, amount); display count is 5 and amount is 45.560000 27

Formatting Output If printing several items in System.out.printf, the format specifiers must be in correct order System.out.printf("%8d%5.2f", 123, 3.45); // Correct: integer first, then float System.out.printf("%8d%5.2f", 3.45, 123); // Error CS4500/5500 UC. Colorado Springs

Summary Math class and methods Characters Strings CS1150 UC. Colorado Springs