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

Similar documents
Course PJL. Arithmetic Operations

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

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

More about JOptionPane Dialog Boxes

CT 229 Fundamentals of Java Syntax

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

Chapter 2 ELEMENTARY PROGRAMMING

CS 106 Introduction to Computer Science I

CST141 Thinking in Objects Page 1

Java s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"

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

CS 106 Introduction to Computer Science I

Data Types Reference Types

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

String. Other languages that implement strings as character arrays

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.

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

Chapter 2 Primitive Data Types and Operations

Chapter 2: Using Data

Introduction to Computers and Engineering Problem Solving 1.00 / Fall 2004

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

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

CP122 Computer Science I. Chapter 2: Data Types, Variables, and I/O

CS 106 Introduction to Computer Science I

Full file at

CS 1301 Ch 8, Part A

Chapter 02: Using Data

Full file at

Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

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

In this lab, you will be given the implementation of the classes GeometricObject, Circle, and Rectangle, as shown in the following UML class diagram.

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

Chapter 2 Primitive Data Types and Operations. Objectives

Full file at

Introduction to Java. Nihar Ranjan Roy.

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

Basic Computation. Chapter 2

Chapter 2 Primitive Data Types and Operations

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

Chapter 2 Elementary Programming

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Fundamental Java Syntax Summary Sheet for CISC124, Fall Java is Case - Sensitive!

Program Fundamentals

DATA TYPES AND EXPRESSIONS

Programming with Java

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

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

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

Date: Dr. Essam Halim

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

CS251L REVIEW Derek Trumbo UNM

Chapter 3 - Introduction to Java Applets

Chapter 3 Selection Statements

Values and Variables 1 / 30

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Using System.out.println()

Topics. The Development Process

MODULE 02: BASIC COMPUTATION IN JAVA

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

JOptionPane Dialogs. javax.swing.joptionpane is a class for creating dialog boxes. Has both static methods and instance methods for dialogs.

Chapter 2 Elementary Programming

Java Fall 2018 Margaret Reid-Miller

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

Big Java. Fifth Edition. Chapter 3 Fundamental Data Types. Cay Horstmann

4 WORKING WITH DATA TYPES AND OPERATIONS

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

Fundamental Java Syntax Summary Sheet for CISC101, Spring Java is Case - Sensitive!

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

3chapter C ONTROL S TATEMENTS. Objectives

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

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

Lecture Notes for CS 150 Fall 2009; Version 0.5

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

Module 4: Characters, Strings, and Mathematical Functions

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Introduction to Java Applications

Eng. Mohammed S. Abdualal

Interaction with Android

STUDENT LESSON A10 The String Class

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

5/24/2006. Last Time. Announcements. Today. Method Overloading. Method Overloading - Cont. Method Overloading - Cont. (Midterm Exam!

Computer Science 145 Midterm 1 Fall 2016

Using Java Classes Fall 2018 Margaret Reid-Miller

Introduction to Classes and Objects

Chapter 12 Strings and Characters. Dr. Hikmat Jaber

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

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

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

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

What two elements are usually present for calculating a total of a series of numbers?

Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto

Programming with Java

CEN 414 Java Programming

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

Transcription:

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 1 of 6 Handout 3 Strings and String Class. Input/Output with JOptionPane. Strings In Java strings are represented with a class type String. Examples: 1. objects of class string: This is a short string a // different from a // an empty string 123.5 2. Declaring a variable of class String, assigning values to string variables, Concatenation operator (+). String name, lastname; name = John ; lastname = Lennon ; String thebeatle = name + + lastname; 3. Primitive type values that are concatenated with a string are converted into strings automatically, so String name = John + 3.2; Stores John3.2 in name What does the following segment print? String resone = 5 and 3 + 5 + 3; String restwo = 5 and 3 + (5 + 3); System.out.println (resone); System.out.println (restwo); Variables of class type store references to the object. String is a class type, so variables of type String store a reference to the actual string object, depicted below. For Example 1 from above. name lastname J o h n L e n n o n Characters within the string are indexed (i.e. numbered) starting with 0. The index of a character within a string is its position (counting from 0). The length of a string is equal to the number of characters in it. String methods (see chart on page 38-41) include methods for: - 1 -

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 2 of 6 finding out the length (i.e. number of characters in a string) - length() extracting a character at a certain position charat(position) replacing a character with another replace (oldchar, newchar) extracting a substring at given position substring(start), substring(start, End) checking if a string contains another as a substring: contains (astr) searching for a substring: contains (astr), indexof (astr), indexof(astr, Start), lastindexof (astr), lastindexof(astr, Start) changing letter case: touppercase(), tolowercase() string comparison equals (anotherstr), compareto(anotherstring) Most of these methods require parameters to be passed, and return a certain value. /* Demo program on String methods: */ public class StringMethodsDemo { public static void main (String[] args) { String phone = " 781-345-4758 "; // remove spaces before and after phone = phone.trim(); System.out.println("\""+ phone + "\""); // Searching methods: System.out.println(" contains a dash? " + phone.contains("-")); System.out.println(" contains \"foo\"? " + phone.contains("foo")); // Find the position of the first dash int posfirstdash = phone.indexof("-"); int poslastdash = phone.lastindexof("-"); // last dash System.out.println("Dashes at positions "+ posfirstdash + " and " + poslastdash); int posdashafterfirst = phone.indexof("-", posfirstdash+1); System.out.println("Second dash at position "+ posdashafterfirst); // Find the position of "475" System.out.println("475 is at position " + phone.indexof("475")); System.out.println("*** is at position " + phone.indexof("***")); // prints -1 // Extract the part between the two dashes String inbetweendashes = phone.substring(posfirstdash+1, posdashafterfirst); System.out.println(inBetweenDashes); // Compare two strings alphabetically String one = "apple", two = "arithmetic", three = "apple"; System.out.println(one.compareToIgnoreCase(two)); System.out.println(two.compareToIgnoreCase(one)); // Compare for equality System.out.println(one.equals(two)); System.out.println(one.equals(three)); Example: Notice the syntax of invoking a String method (see examples from class) - 2 -

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 3 of 6 Note: When comparing the content of two strings for equality use the equals method! (Do not use == ). The equals() method returns a boolean value, true or false. Example: String strone, strtwo; Scanner kbrd = new Scanner(System.in); System.out.println( Please enter two strings. ); strone = kbrd.nextline(); strtwo = kbrd.nextline(); System.out.println(strOne + is the same as + strtwo)); System.out.println( is + strone.equals(strtwo)); Practice problems: A course ID is a string that has the following format: it starts with two letters followed by the dash ( - ) and any number of digits, e.g. CS-230, MA-1220, CH- 12. Write a program that reads in a course ID from the user and prints out the number part of the ID separately. How would you extract the letter and the number parts of a course ID that may have any number of letters, followed by a single dash and any number of digits, e.g. COMP-230, LIT-31, MATH-645? - 3 -

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 4 of 6 String methods practice: in one java main method include the code to do the following (in parentheses I ve included the String methods that would be helpful for each task. It may be possible to accomplish each task using other methods): 1. Given a string that contains a phone number, except without dashes, e.g. 7813456789, compose another string that contains the phone with the dashes: 781-345-6789. (+, substring) 2. Given a string, compose another one, which contains the first character and the last character, in uppercase. For example, for string Bentley, the resulting string should be BY. (substring, charat, length, touppercase, +), 3. Given a string of even length, produce the second half. So the string "WooHoo" yields "Hoo". (substring, length) 4. Given a string containing a sentence with parentheses, print out the test inside parentheses, removing all surrounding spaces; for example, given "There was snow ( a lot of it! ) last week." Output a lot of it! (indexof, substring, trim) 5. Given a string of text, replace all space characters with dashes, e.g. for "There was snow the output should be There-was-snow. (replace) 6. Given a word that contains letter a, e.g. blackboard produce one that has two letters after the first a capitalized, i.e. blackboard (indexof, substring, touppercase). 7. Given a string of text with several words, e.g. brevity is the soul of wit change it so that it has a. the first word capitalized, i.e. BREVITY is the soul of wit, b. the last word capitalized, i.e. brevity is the soul of WIT c. the first two words capitalized BREVITY IS the soul of wit. - 4 -

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 5 of 6 Input/Output using JOptionPane JOptionPane class provides methods for input/output via a pop-up window. Methods: o showinputdialog o showmessagedialog part of the Swing package predefined collection of classes that comes with the Java distribution the package must be explicitly imported using the import statement that comes before the class definition: import javax.swing.joptionpane; // imports class JOptionPane Alternatively, to import all classes from a package: import javax.swing.*; //imports all classes in the swing pckg. For both showinputdialog and showmessagedialog methods Note the calling convention - must precede name of method with its class name JOptionPane.showInputDialog( prompt for input here ); JOptionPane.showMessageDialog(null,"Hello World! ); Window becomes invisible after user clicks ok button. The program must be terminated using the following statement (last statement of the main method); System.exit(0);// ends program and releases resources The 0 indicates normal termination Example: import javax.swing.joptionpane; // or import javax.swing.*; /* Get user input as a String. */ public class JOptionPaneSimple { public static void main(string [] args) { // get user input as a string String strin = JOptionPane.showInputDialog("Enter a string"); System.out.println("The user entered: " + strin); JOptionPane.showMessageDialog(null, "The user entered: " + strin); System.exit(0); //must be the last statement of main if // JOptionPane methods are used - 5 -

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 6 of 6 The next example demonstrates how to convert the entered string into a number type. import javax.swing.joptionpane; public class JOptionPaneDemo { public static void main(string[] args) { String podstring = JOptionPane.showInputDialog("Enter number of pods:"); // convert string stored in podstring into an integer number int numberofpods = Integer.parseInt(podString); // if user input was not a whole number, a RUN-TIME error // will occur while executing the above line. //This can also be done as follows (combine two method calls) int peasperpod = Integer.parseInt(JOptionPane.showInputDialog( "Enter number of peas in a pod:")); int totalnumberofpeas = numberofpods*peasperpod; JOptionPane.showMessageDialog(null, "The total number of peas = " + totalnumberofpeas); System.exit(0); Summary: JOptionPane.showInputDialog() method Displays a popup window for accepting user input Takes one parameter the string to be displayed in the pop-up window Returns user input as a String To convert input to an integer, or double, etc.. must call the converter methods Integer.parseInt() Double.parseDouble() JOptionPane.showMessageDialog() method Displays a popup window for displaying messages, such as output Takes two parameters Precede name of method with its class name if using it within a different class JOptionPane.showMessageDialog(null, put output here ); The null value tells Java to create a default window for showing the dialog. Also requires System.exit(0); for proper termination. - 6 -