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



Similar documents
CS 106 Introduction to Computer Science I

Sample CSE8A midterm Multiple Choice (circle one)

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

AP Computer Science Static Methods, Strings, User Input

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

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

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

Chapter 2: Elements of Java

Introduction to Java Applets (Deitel chapter 3)

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

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

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

Computer Programming I

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

Introduction to Java. CS 3: Computer Programming in Java

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

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

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

Chapter 2 Elementary Programming

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

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

AP Computer Science Java Subset

Lecture 5: Java Fundamentals III

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

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

Chapter 2 Introduction to Java programming

Week 1: Review of Java Programming Basics

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

Introduction to Java

java Features Version April 19, 2013 by Thorsten Kracht

Comp 248 Introduction to Programming

WRITING DATA TO A BINARY FILE

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Introduction to Object-Oriented Programming

Building Java Programs

CS106A, Stanford Handout #38. Strings and Chars

Text file I/O and simple GUI dialogues

Introduction to Programming

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

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

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

LAB 3 Part 1 OBJECTS & CLASSES

Web Programming Step by Step

Unit 6. Loop statements

Building Java Programs

Part 1 Foundations of object orientation

Using Files as Input/Output in Java 5.0 Applications

Install Java Development Kit (JDK) 1.8

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

Java Basics: Data Types, Variables, and Loops

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Moving from CS 61A Scheme to CS 61B Java

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Explain the relationship between a class and an object. Which is general and which is specific?

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

For live Java EE training, please see training courses

Chapter 1. Introduction to Computers, Programs, and Java

Interactive Applications (CLI) and Math

Topic 11 Scanner object, conditional execution

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Microsoft Access 3: Understanding and Creating Queries

Basic Java Syntax. Slides 2016 Marty Hall,

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

Introduction to Java Lecture Notes. Ryan Dougherty

Java CPD (I) Frans Coenen Department of Computer Science

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

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

JavaScript Introduction

Building Java Programs

How to Install Java onto your system

Basics of Java Programming Input and the Scanner class

Graphical User Interfaces

Exercise 1: Python Language Basics

Iteration CHAPTER 6. Topic Summary

Some Scanner Class Methods

Chapter 3. Input and output. 3.1 The System class

CS170 Lab 11 Abstract Data Types & Objects

Text Processing In Java: Characters and Strings

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Arrays. Introduction. Chapter 7

Variables, Constants, and Data Types

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

Object Oriented Software Design

Programming Fundamentals I CS 110, Central Washington University. November 2015

Building Java Programs

Basic Object-Oriented Programming in Java

CS 106 Introduction to Computer Science I

13 File Output and Input

CS506 Web Design and Development Solved Online Quiz No. 01

Primitive data types in Java

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

6.1. Example: A Tip Calculator 6-1

Building Java Programs

Chapter 2 Basics of Scanning and Conventional Programming in Java

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

JAVA ARRAY EXAMPLE PDF

Example of a Java program

Transcription:

Handout 3 cs180 - Programming Fundamentals Spring 15 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 Spring 15 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 Spring 15 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 Spring 15 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 Spring 15 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 Spring 15 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 -