Building Java Programs

Similar documents
Building Java Programs

Building Java Programs Chapter 4

Topic 13 procedural design and Strings

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Building Java Programs

Building Java Programs

Topic 12 more if/else, cumulative algorithms, printf

Building Java Programs

CS 112 Introduction to Programming

Sierpinski Valentine.

Lecture 8: The String Class and Boolean Zen

Sierpinski Valentine. q Our journey of introducing conditionals

Topic 12 more if/else, cumulative algorithms, printf

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Topic 23 arrays - part 3 (tallying, text processing)

Returns & if/else. Parameters and Objects

CSE 373. Data Types and Manipulation; Arrays. slides created by Marty Stepp

CS 112 Introduction to Programming

Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs

Text processing. Readings: 4.4

CSc 110, Autumn Lecture 11: Strings. Adapted from slides by Marty Stepp and Stuart Reges

Topic 4 Expressions and variables

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Text processing. Characters. The charat method. Fun with char! char vs. String. Text processing. Readings: 4.4 (pg ) 'h' is a char

Lecture 2: Operations and Data Types

CS 5010: Programming Design Paradigms!

Building Java Programs Chapter 3

Redundant recipes. Building Java Programs Chapter 3. Parameterized recipe. Redundant figures

More on variables and methods

Building Java Programs Chapter 2

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Full file at

Lecture 4: Conditionals

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

Building Java Programs

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2

AP Computer Science. if/else, return values. Copyright 2010 by Pearson Education

CS 112 Introduction to Programming

Chapter 1 Introduction to java

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

AP Computer Science A

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

CSc 110, Spring Lecture 10: Strings. Adapted from slides by Marty Stepp and Stuart Reges

Building Java Programs

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

Place your name tag here

CS 106 Introduction to Computer Science I

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

CS 106A, Lecture 9 Problem-Solving with Strings

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

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

MODULE 02: BASIC COMPUTATION IN JAVA

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

CSc 110, Spring Lecture 14: Booleans and Strings. Adapted from slides by Marty Stepp and Stuart Reges

Mr. Monroe s Guide to Mastering Java Syntax

Topic 11 Scanner object, conditional execution

STUDENT LESSON A10 The String Class

Midterm Examination (MTA)

DATA TYPES AND EXPRESSIONS

Module 4: Characters, Strings, and Mathematical Functions

CSE 142, Spring Chapters 6 and 7 Line-Based File Input, Arrays. reading: , 7.1

Welcome to the Using Objects lab!

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Chapter 2: Review Exercise Solutions R2.1

Example: Monte Carlo Simulation 1

CMPT 125: Lecture 3 Data and Expressions

Building Java Programs

CS 106A, Lecture 9 Problem-Solving with Strings

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

CSc 110, Autumn Lecture 14: Strings. Adapted from slides by Marty Stepp and Stuart Reges

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

Introduction to Computer Programming

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Question: Total Points: Score:

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

Building Java Programs

JAVA OPERATORS GENERAL

Using Java Classes Fall 2018 Margaret Reid-Miller

Lec 3. Compilers, Debugging, Hello World, and Variables

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

Chapter 3: Operators, Expressions and Type Conversion

CIS October 19, 2017

Midterm Review Session

Building Java Programs

Question: Total Points: Score:

Creating Strings. String Length

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Console Input and Output

Computational Expression

Topic 11 Scanner object, conditional execution

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Chapter 2 ELEMENTARY PROGRAMMING

Transcription:

Building Java Programs Chapter 4 Lecture 4-3: Strings; char; printf; procedural design reading: 3.3, 4.3, 4.5 1 Strings reading: 3.3 1

Strings string: An object storing a sequence of text characters. Unlike most other objects, a String is not created with new. String <name> = "<text>"; String <name> = <expression with String value>; Examples: String name = "Glen Hansard"; int x = 3; int y = 5; String point = "(" + x + ", " + y + ")"; 3 Indexes Characters of a string are numbered with 0-based indexes: String name = "M. Mouse"; index 0 1 2 3 4 5 6 7 character M. M o u s e First character's index : 0 Last character's index : 1 less than the string's length The individual characters are values of type char (seen later) 4 2

String methods Method name indexof(<string>) length() substring(<index1>, <index2>) or substring(<index1>) tolowercase() touppercase() Description index where the start of the given string appears in this string (-1 if not found) number of characters in this string the characters in this string from index1 (inclusive) to index2 (exclusive); if index2 is omitted, grabs until end of string a new string with all lowercase letters a new string with all uppercase letters These methods are called using the dot notation: String popstarz = "Prince vs. Michael"; System.out.println(popStarz.length()); // 18 5 String method examples // index 012345678901 String s1 = "Stuart Reges"; String s2 = "Marty Stepp"; System.out.println(s1.length()); // 12 System.out.println(s1.indexOf("e")); // 8 System.out.println(s1.substring(7, 10)); // "Reg" String s3 = s2.substring(1, 7); System.out.println(s3.toLowerCase()); // "arty s" Given the following string: // index 0123456789012345678901 String book = "Building Java Programs"; How would you extract the word "Java"? 6 3

Modifying strings Methods like substring and tolowercase build and return a new string, rather than modifying the current string. String s = "Mumford & Sons"; s.touppercase(); System.out.println(s); // Mumford & Sons To modify a variable's value, you must reassign it: String s = "Mumford & Sons"; s = s.touppercase(); System.out.println(s); // MUMFORD & SONS 7 Strings as user input Scanner's next method reads a word of input as a String. Scanner console = new Scanner(System.in); System.out.print("What is your name? "); String name = console.next(); name = name.touppercase(); System.out.println(name + " has " + name.length() + " letters and starts with " + name.substring(0, 1)); Output: What is your name? Bono BONO has 4 letters and starts with B The nextline method reads a line of input as a String. System.out.print("What is your address? "); String address = console.nextline(); 8 4

Strings question Write a program that outputs The Name Game with a person s first and last name. Example Output: What is your name? James Joyce James, James, bo-bames Banana-fana fo-fames Fee-fi-mo-mames JAMES! Joyce, Joyce, bo-boyce Banana-fana fo-foyce Fee-fi-mo-moyce JOYCE! 9 Strings answer // This program prints "The Name Game". import java.util.*; public class TheNameGame { public static void main(string[] args) { Scanner console = new Scanner(System.in); System.out.print("What is your name? "); String name = console.nextline(); int spaceindex = name.indexof(" "); String firstname = name.substring(0, spaceindex); String lastname = name.substring(spaceindex + 1); singsong(firstname); singsong(lastname); 10 5

Strings answer (cont.) public static void singsong(string name) { System.out.println(); String allbutfirst = name.substring(1); System.out.println(name + ", " + name + ", bo-b" + allbutfirst); System.out.println("Banana-fana fo-f" + allbutfirst); System.out.println("Fee-fi-mo-m" + allbutfirst); System.out.println(name.toUpperCase() + "!"); 11 Comparing strings Relational operators such as < and == fail on objects. Scanner console = new Scanner(System.in); System.out.print("What is your name? "); String name = console.next(); if (name == "Barney") { System.out.println("I love you, you love me,"); System.out.println("We re a happy family!"); This code will compile, but it will not print the song. == compares objects by references (seen later), so it often gives false even when two Strings have the same letters. 12 6

The equals method Objects are compared using a method named equals. Scanner console = new Scanner(System.in); System.out.print("What is your name? "); String name = console.next(); if (name.equals("barney")) { System.out.println("I love you, you love me,"); System.out.println("We re a happy family!"); Technically this is a method that returns a value of type boolean, the type used in logical tests. 13 String test methods Method equals(<str>) Description whether two strings contain the same characters equalsignorecase(<str>) whether two strings contain the same characters, ignoring upper vs. lower case startswith(<str>) endswith(<str>) contains(<str>) whether one contains other's characters at start whether one contains other's characters at end whether the given string is found within this one String name = console.nextline(); if (name.endswith("yeats")) { System.out.println("Say my glory was I had such friends."); else if (name.equalsignorecase("oscar WILDE")) { System.out.println("A true friend stabs you in the front."); 14 7

char reading: 4.3 Type char char : A primitive type representing single characters. A String is stored internally as an array of char String s = "nachos"; index 0 1 2 3 4 5 value 'n' 'a' 'c' 'h' 'o' 's' It is legal to have variables, parameters, returns of type char surrounded with apostrophes: 'a' or '4' or '\n' or '\'' char initial = 'J'; System.out.println(initial); // J System.out.println(initial + " Joyce"); // J Joyce 16 8

The charat method The chars in a String can be accessed using the charat method. accepts an int index parameter and returns the char at that index String food = "cookie"; char firstletter = food.charat(0); // 'c' System.out.println(firstLetter + " is for " + food); You can use a for loop to print or examine each character. String major = "CSE"; for (int i = 0; i < major.length(); i++) { // output: char c = major.charat(i); // C System.out.println(c); // S // E 17 Comparing char values You can compare chars with ==,!=, and other operators: String word = console.next(); char last = word.charat(word.length() - 1); if (last == 's') { System.out.println(word + " is plural."); // prints the alphabet for (char c = 'a'; c <= 'z'; c++) { System.out.print(c); 18 9

char vs. int Each char is mapped to an integer value internally Called an ASCII value 'A' is 65 'B' is 66 ' ' is 32 'a' is 97 'b' is 98 '*' is 42 Mixing char and int causes automatic conversion to int. 'a' + 10 is 107, 'A' + 'A' is 130 To convert an int into the equivalent char, type-cast it. (char) ('a' + 2) is 'c' 19 char vs. String "h" is a String, but 'h' is a char (they are different) A String is an object; it contains methods. String s = "h"; s = s.touppercase(); // "H" int len = s.length(); // 1 char first = s.charat(0); // 'H' A char is primitive; you can't call methods on it. char c = 'h'; c = c.touppercase(); s = s.charat(0).touppercase(); What is s + 1? What is c + 1? What is s + s? What is c + c? // ERROR // ERROR 20 10

printf reading: 4.3 Formatting text with printf System.out.printf("<format string>", <parameters>); A format string can contain placeholders to insert parameters: %d integer %f real number %s string %c character (these placeholders are used instead of + concatenation) Example: int x = 3; int y = -17; System.out.printf("x is %d and y is %d!\n", x, y); // x is 3 and y is -17! Note: printf does not drop to the next line unless you write \n 22 11

printf width %Wd %-Wd %Wf... integer, W characters wide, right-aligned integer, W characters wide, left-aligned real number, W characters wide, right-aligned for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 10; j++) { System.out.printf("%4d", (i * j)); System.out.println(); // to end the line Output: 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 23 printf precision %.Df %W.Df %-W.Df real number, rounded to D digits after decimal real number, W chars wide, D digits after decimal real number, W wide (left-align), D after decimal double gpa = 3.253764; System.out.printf("your GPA is %.1f\n", gpa); System.out.printf("more precisely: %8.3f\n", gpa); Output: 3 your GPA is 3.3 more precisely: 3.254 8 24 12

printf question Modify our Receipt program to better format its output. Display results in the format below, with 2 digits after. Example log of execution: How many people ate? 4 Person #1: How much did your dinner cost? 20.00 Person #2: How much did your dinner cost? 15 Person #3: How much did your dinner cost? 25.0 Person #4: How much did your dinner cost? 10.00 Subtotal: $70.00 Tax: $5.60 Tip: $10.50 Total: $86.10 25 printf answer (partial)... // Calculates total owed, assuming 8% tax and 15% tip public static void results(double subtotal) { double tax = subtotal *.08; double tip = subtotal *.15; double total = subtotal + tax + tip; // System.out.println("Subtotal: $" + subtotal); // System.out.println("Tax: $" + tax); // System.out.println("Tip: $" + tip); // System.out.println("Total: $" + total); System.out.printf("Subtotal: $%.2f\n", subtotal); System.out.printf("Tax: $%.2f\n", tax); System.out.printf("Tip: $%.2f\n", tip); System.out.printf("Total: $%.2f\n", total); 26 13

Procedural design reading: 4.5 Recall: BMI program Formula for body mass index (BMI): BMI weight height 703 2 BMI Weight class below 18.5 underweight 18.5-24.9 normal 25.0-29.9 overweight 30.0 and up obese Write a program that produces output like the following: This program reads data for two people and computes their body mass index (BMI). Enter next person's information: height (in inches)? 70.0 weight (in pounds)? 194.25 Enter next person's information: height (in inches)? 62.5 weight (in pounds)? 130.5 Person 1 BMI = 27.868928571428572 overweight Person 2 BMI = 23.485824 normal Difference = 4.3831045714285715 28 14

"Chaining" main should be a concise summary of your program. It is bad if each method calls the next without ever returning (we call this chaining): main methoda methodb methodc methodd A better structure has main make most of the calls. Methods must return values to main to be passed on later. main methoda methodb methodd methodc 29 Bad "chain" code public class BMI { public static void main(string[] args) { System.out.println("This program reads... (etc.)"); Scanner console = new Scanner(System.in); person(console); public static void person(scanner console) { System.out.println("Enter next person's information:"); System.out.print("height (in inches)? "); double height = console.nextdouble(); getweight(console, height); public static void getweight(scanner console, double height) { System.out.print("weight (in pounds)? "); double weight = console.nextdouble(); computebmi(console, height, weight); public static void computebmi(scanner s, double h, double w) {... 30 15

Procedural heuristics 1. Each method should have a clear set of responsibilities. 2. No method should do too large a share of the overall task. 3. Minimize coupling and dependencies between methods. 4. The main method should read as a concise summary of the overall set of tasks performed by the program. 5. Data should be declared/used at the lowest level possible. 31 16