Building Java Programs

Similar documents
Building Java Programs

Building Java Programs

Topic 11 Scanner object, conditional execution

Chapter 2 Introduction to Java programming

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

Sample CSE8A midterm Multiple Choice (circle one)

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Introduction to Java. CS 3: Computer Programming in Java

Unit 6. Loop statements

Building Java Programs

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Building Java Programs

Introduction to Java

Week 1: Review of Java Programming Basics

CS106A, Stanford Handout #38. Strings and Chars

Building Java Programs

Text Processing In Java: Characters and Strings

Introduction to Object-Oriented Programming

Line-based file processing

Web Programming Step by Step

AP Computer Science Static Methods, Strings, User Input

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

J a v a Quiz (Unit 3, Test 0 Practice)

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Building Java Programs

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Install Java Development Kit (JDK) 1.8

The following program is aiming to extract from a simple text file an analysis of the content such as:

Chapter 2 Basics of Scanning and Conventional Programming in Java

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

AP Computer Science File Input with Scanner

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Chapter 2: Elements of Java

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Building Java Programs

Building Java Programs

Introduction to Java Lecture Notes. Ryan Dougherty

Computer Programming I

Introduction to Programming

CS 121 Intro to Programming:Java - Lecture 11 Announcements

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Moving from CS 61A Scheme to CS 61B Java

LAB 3 Part 1 OBJECTS & CLASSES

Arrays. Introduction. Chapter 7

Using Files as Input/Output in Java 5.0 Applications

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Lecture 5: Java Fundamentals III

Object Oriented Software Design

Comp 248 Introduction to Programming

Part I. Multiple Choice Questions (2 points each):

Java Basics: Data Types, Variables, and Loops

Variables, Constants, and Data Types

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Some Scanner Class Methods

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

public static void main(string[] args) { System.out.println("hello, world"); } }

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

Programming in Java Course Technology, a part of Cengage Learning.

For live Java EE training, please see training courses

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

AP Computer Science Java Subset

Chapter 2 Elementary Programming

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Basics of Java Programming Input and the Scanner class

java Features Version April 19, 2013 by Thorsten Kracht

Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:

Chapter 3. Input and output. 3.1 The System class

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

CS170 Lab 11 Abstract Data Types & Objects

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

6.1. Example: A Tip Calculator 6-1

LOOPS CHAPTER CHAPTER GOALS

CS 106 Introduction to Computer Science I

Object-Oriented Programming in Java

Basic Object-Oriented Programming in Java

Topic 16 boolean logic

Java CPD (I) Frans Coenen Department of Computer Science

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

Interactive Applications (CLI) and Math

While and Do-While Loops Summer 2010 Margaret Reid-Miller

Pemrograman Dasar. Basic Elements Of Java

Programming Languages CIS 443

JAVA ARRAY EXAMPLE PDF

D06 PROGRAMMING with JAVA

More on Objects and Classes

Example of a Java program

Programming and Data Structures with Java and JUnit. Rick Mercer

Continuous Integration Part 2

Transcription:

Building Java Programs Chapter 4 Lecture 10: Strings, char reading: 3.3, 4.3 (Slides adapted from Stuart Reges, Hélène Martin, and Marty Stepp) 1

2

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; Examples: String name = "Marla Singer"; int x = 3; int y = 5; String point = "(" + x + ", " + y + ")"; 3

Indexes Characters of a string are numbered with 0-based indexes: String name = "Ultimate"; index 0 1 2 3 4 5 6 7 character U l t i m a t 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

String methods indexof(str) length() Method name 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 till 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 starz = "Yeezy & Hova"; System.out.println(starz.length()); // 12 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

Modifying strings Methods like substring and tolowercase build and return a new string, rather than modifying the current string. String s = "Aceyalone"; s.touppercase(); System.out.println(s); // Aceyalone To modify a variable's value, you must reassign it: String s = "Aceyalone"; s = s.touppercase(); System.out.println(s); // ACEYALONE 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? Nas NAS has 3 letters and starts with N The nextline method reads a line of input as a String. System.out.print("What is your address? "); String address = console.nextline(); 8

Strings question Write a program that reads two people's first names and suggests a name for their child Example Output: Parent 1 first name? Danielle Parent 2 first name? John Child Gender? f Suggested baby name: JODANI Parent 1 first name? Danielle Parent 2 first name? John Child Gender? Male Suggested baby name: DANIJO 9

Strings answer // Suggests a baby name based on parents' names. import java.util.*; public class BabyNamer { public static void main(string[] args) { Scanner s = new Scanner(System.in); System.out.print("Parent 1 first name? "); String name1 = s.next(); System.out.print("Parent 2 first name? "); String name2 = s.next(); System.out.print("Child Gender? "); String gender = s.next(); String halfname1 = gethalfname(name1); String halfname2 = gethalfname(name2); String name = ""; if(gender.tolowercase().startswith("m")){ name = halfname1 + halfname2; else { name = halfname2 + halfname1; System.out.println("Suggested name: " + name.touppercase());... 10

Strings answer (cont.) public static String gethalfname(string name) { int halfindex = name.length() / 2; String half = name.substring(0, halfindex); return half; 11

Name border HELENE HELEN HELE HEL HE H HE HEL HELE HELEN HELENE MARTIN MARTI MART MAR MA M MA MAR MART MARTI MARTIN Prompt the user for full name Draw out the pattern to the left 12

Name border answer // Prints a user's first name and last name in a wave pattern. import java.util.*; // For Scanner public class NameBorder { public static void main(string[] args) { Scanner console = new Scanner(System.in); System.out.print("Full name? "); String fullname = console.nextline(); int gapindex = fullname.indexof(" "); String firstname = fullname.substring(0, gapindex); String lastname = fullname.substring(gapindex + 1); wavename(firstname); wavename(lastname); // Prints a string in a wave pattern. public static void wavename(string name) { for (int i = name.length(); i >= 1; i--) { System.out.println(name.substring(0, i)); // The 2 avoids printing the 1 character String twice. for (int i = 2; i <= name.length(); i++) { System.out.println(name.substring(0, i)); 13

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 == "Lance") { System.out.println("Pain is temporary."); System.out.println("Quitting lasts forever."); This code will compile, but it will not print the quote. == compares objects by references (seen later), so it often gives false even when two Strings have the same letters. 14

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("lance")) { System.out.println("Pain is temporary."); System.out.println("Quitting lasts forever."); Technically this is a method that returns a value of type boolean, the type used in logical tests. 15

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) whether one contains other's characters at start endswith(str) contains(str) whether one contains other's characters at end whether the given string is found within this one String name = console.next(); if(name.endswith("kweli")) { System.out.println("Pay attention, you gotta listen to hear."); else if(name.equalsignorecase("nas")) { System.out.println("I never sleep 'cause sleep is the cousin of death."); 16

Type char char : A primitive type representing single characters. Each character inside a String is stored as a char value. Literal char values are surrounded with apostrophe (single-quote) marks, such as 'a' or '4' or '\n' or '\'' It is legal to have variables, parameters, returns of type char char letter = 'S'; System.out.println(letter); // S char values can be concatenated with strings. char initial = 'P'; System.out.println(initial + " Diddy"); // P Diddy 17

The charat method The chars in a String can be accessed using the charat method. String food = "cookie"; char firstletter = food.charat(0); // 'c' System.out.println(firstLetter + " is for " + food); System.out.println("That's good enough for me!"); You can use a for loop to print or examine each character. String major = "CSE"; for (int i = 0; i < major.length(); i++) { char c = major.charat(i); System.out.println(c); Output: C S E 18

char vs. String "h" is a String 'h' is a char (the two behave differently) 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' char is primitive; you can't call methods on it char c = 'h'; c = c.touppercase(); // ERROR: "cannot be dereferenced" What is s + 1? What is c + 1? What is s + s? What is c + c? 19

char vs. int All char values are assigned numbers internally by the computer, called ASCII values. Examples: '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' 20

Comparing char values You can compare char values with relational operators: 'a' < 'b' and 'X' == 'X' and 'Q'!= 'q' An example that prints the alphabet: for (char c = 'a'; c <= 'z'; c++) { System.out.print(c); You can test the value of a string's character: String word = console.next(); if (word.charat(word.length() - 1) == 's') { System.out.println(word + " is plural."); 21

String/char question A Caesar cipher is a simple encryption where a message is encoded by shifting each letter by a given amount. e.g. with a shift of 3, A D, H K, X A, and Z C Write a program that reads a message from the user and performs a Caesar cipher on its letters: Your secret message: Brad thinks Angelina is cute Your secret key: 3 The encoded message: eudg wklqnv dqjholqd lv fxwh The decoded message: brad thinks angelina is cute 22

Strings answer 1 // This program reads a message and a secret key from the user and // encrypts the message using a Caesar cipher, shifting each letter. import java.util.*; public class SecretMessage { public static void main(string[] args) { Scanner console = new Scanner(System.in);... System.out.print("Your secret message: "); String message = console.nextline(); message = message.tolowercase(); System.out.print("Your secret key: "); int key = console.nextint(); String encoded = encode(message, key); System.out.println("The encoded message: " + encoded); String decoded = encode(encoded, -key); System.out.println("The decoded message: " + decoded); 23

Strings answer 2 // This method encodes the given text string using a Caesar // cipher, shifting each letter by the given number of places. public static String encode(string text, int shift) { String result = ""; for (int i = 0; i < text.length(); i++) { char letter = text.charat(i); // shift only letters (leave other characters alone) if (letter >= 'a' && letter <= 'z') { letter = (char) (letter + shift); // may need to wrap around if (letter > 'z') { letter = (char) (letter - 26); else if (letter < 'a') { letter = (char) (letter + 26); result += letter; return result; 24