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

Similar documents
Eng. Mohammed Abdualal

Reading Input from Text File

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

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

Module 4: Characters, Strings, and Mathematical Functions

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

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

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

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

Chapter 4 Mathematical Functions, Characters, and Strings

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

Chapter 2 ELEMENTARY PROGRAMMING

Programming with Java

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

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

Chapter 12 Strings and Characters. Dr. Hikmat Jaber

Introduction to Computers. Laboratory Manual. Experiment #3. Elementary Programming, II

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Computational Expression

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

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

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

Chapter 4. Mathematical Functions, Characters, and Strings

Full file at

Welcome to the Using Objects lab!

Introduction to Java Applications

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

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

Chapter 2 Elementary Programming

c) And last but not least, there are javadoc comments. See Weiss.

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

AP Computer Science A

CEN 414 Java Programming

Java Console Input/Output The Basics

Basic Computation. Chapter 2

Input. Scanner keyboard = new Scanner(System.in); String name;

Computer Programming: C++

Full file at

Basic Computation. Chapter 2

STUDENT LESSON A10 The String Class

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

We now start exploring some key elements of the Java programming language and ways of performing I/O

Eng. Mohammed S. Abdualal

CS 211: Existing Classes in the Java Library

Using Java Classes Fall 2018 Margaret Reid-Miller

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

Strings. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

More on variables and methods

Computer Programming, I. Laboratory Manual. Final Exam Solution

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

Chapter 2 Primitive Data Types and Operations. Objectives

STUDENT LESSON A7 Simple I/O

JAVA PROGRAMMING LAB. ABSTRACT EXTRA LAB, In this Lab you will learn working with recursion, JRX, Java documentations

First Java Program - Output to the Screen

Eng. Mohammed Abdualal

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

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

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

CST242 Strings and Characters Page 1

Introduction to Java Applications; Input/Output and Operators

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Elementary Programming

BASIC ELEMENTS OF A COMPUTER PROGRAM

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

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

Welcome to the Using Objects lab!

Computer Programming, I. Laboratory Manual. Experiment #9. Multi-Dimensional Arrays

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

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

when you call the method, you do not have to know exactly what those instructions are, or even how the object is organized internally

4 WORKING WITH DATA TYPES AND OPERATIONS

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

Assignment 2.4: Loops

Chapter 2 Primitive Data Types and Operations

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

Chapter 2: Basic Elements of Java

CSE20 : Lab #4 - Data Types

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

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

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

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Object Oriented Programming. Java-Lecture 1

IT 374 C# and Applications/ IT695 C# Data Structures

2.8. Decision Making: Equality and Relational Operators

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

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

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Computational Expression

Methods. Eng. Mohammed Abdualal

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

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

Computer Programming : C++

Lecture Set 2: Starting Java

Chapter 9 Strings and Text I/O

Transcription:

Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #5 Strings & Text Files Input

The String Data Type The char type represents only one character. A string is a sequence of characters. To represent a string of characters, use the data type called String. A sequence of characters is enclosed in double quotation marks. Example: String message = "Welcome to Java"; String is a predefined class in the Java library. just like the classes System and Scanner. It contains many useful methods manipulating characters. The following table lists the String methods for obtaining string length, for accessing characters in the string, for concatenating strings, for converting a string to upper or lowercases, and for trimming a string. Strings are objects in Java. The methods in the table above can only be invoked from a specific string instance. For this reason, these methods are called instance methods. A non-instance method is called a static method. A static method can be invoked using the class name, without using an object. All the methods defined in the Math class are static methods. They are not tied to a specific object instance. Getting Characters from a String The str.charat(index) method can be used to retrieve a specific character in a string s, where the index is between 0 and s.length() 1. For example, message.charat(0) returns the character W, as shown in the next figure. Note that the index for the first character in the string is 0. 2

Note that attempting to access characters in a string s out of bounds is a common programming error. To avoid it, make sure that you do not use an index beyond s.length() 1. Reading a String from the Console To read a string from the console, invoke the next() method on a Scanner object. The next() method reads a string that ends with a whitespace character. You can use the nextline() method to read an entire line of text. The nextline() method reads a string that ends with the Enter key pressed. Also, you can read characters from the console using the following statement: char c = input.nextline().charat(0); Ex: Write a Java program to prompt the user to enter a line and output the following: How many characters in the line? The fifth character (if exists) All characters in uppercase All characters in lowercase Solution: 3

Scanner input = new Scanner(System.in); String s = input.nextline(); s = s.trim(); int length = s.length(); System.out.println("Length is: " + length); if (length >= 5) System.out.println("Fifth character is: " + s.charat(4)); else System.out.println("The fifth character does not exist"); System.out.println("Uppercase: " + s.touppercase()); System.out.println("Lowercase: " + s.tolowercase()); Comparing Strings The String class contains the following methods for comparing two strings. Obtaining Substrings You can obtain a substring from a string using the substring method. For example: String message = "Welcome to Java"; String message = message.sustring(0, 11)+"HTML"; The string message now becomes "Welcome to HTML" Note that the last character (11) is excluded. 4

Finding a Character or a Substring in a String The String class provides several versions of "indexof" and "lastindexof" methods to find a character or a substring in a string, as shown in the following table: Note that all the previous methods return -1 if not matched. Examples: "Welcome to Java".indexOf('W') returns 0 "Welcome to Java".indexOf('o') returns 4 "Welcome to Java".indexOf('o', 5) returns 9 "Welcome to Java".indexOf("come") returns 3 "Welcome to Java".indexOf("Java", 5) returns 11 "Welcome to Java".indexOf("java", 5) returns -1 "Welcome to Java".lastIndexOf('W') returns 0 "Welcome to Java".lastIndexOf('o') returns 9 "Welcome to Java".lastIndexOf('o', 5) returns 4 "Welcome to Java".lastIndexOf("come") returns 3 "Welcome to Java".lastIndexOf("Java", 5) returns -1. "Welcome to Java".lastIndexOf("Java") returns 11 5

Ex: Write a Java program to prompt the user to enter his full name as FirstName LastName, and the program prints each word in a line. Solution: Scanner input = new Scanner(System.in); String name = input.nextline(); int sp = name.indexof(" "); String firstname = name.substring(0, sp); String lastname = name.substring(sp + 1); System.out.println("First Name is: " + firstname); System.out.println("Last Name is: " + lastname); Other Solution: Scanner input = new Scanner(System.in); String firstname = input.next(); String lastname = input.next(); System.out.println("First Name is: " + firstname); System.out.println("Last Name is: " + lastname); Conversion between Strings and Numbers To convert a string into an int value, use the Integer.parseInt method, as follows: int intvalue = Integer.parseInt(intString); To convert a string into a double value, use the Double.parseDouble method, as follows: double doublevalue = Double.parseDouble(doubleString); You can convert a number into a string, simply use the string concatenating operator as follows: String s = number + ""; Formatting Console Output You can use the System.out.printf method to display formatted output on the console. 6

For example, in the following code the interest amount is currency and it should be displayed in two digits after the decimal point. double amount = 12618.98; double interestrate = 0.0013; double interest = amount * interestrate; System.out.println("Interest is $" + interest); Interest is $16.404674 So, we use the method printf with the format specifier %5.2f double amount = 12618.98; double interestrate = 0.0013; double interest = amount * interestrate; System.out.printf("Interest is $%5.2f", interest); Interest is $16.40 The 5 is the number of digits (including decimal point), and 2 is the number of digits after the decimal point. f is used to tell the formatter that the string is of type float. The syntax to invoke this method is System.out.printf(format, item1, item2,..., itemk) where format is a string that may consist of substrings and format specifiers. Reading Input from Text File The simplest mechanism for reading an external text file is to use Scanner Class. You already know to use Scanner for reading console input. Instead of System.in, you first connect the file with a File object (defined in java.io package), then use that File object to construct a Scanner object. File f = new File("input.txt"); Scanner input = new Scanner(f); This Scanner object (input) reads text from the file "input.txt." You can use the Scanner methods, such as next(), nextint(), nextline(), nextdouble(),to read data from the input file. 7

input.next(); // read a string (one word only) delimited by a //white-space (space, tab, newline) input.nextint(); // read an integer input.nextdouble(); // read a double input.nextline(); // read a string (the whole line) Note that the file input.txt must be in the main directory of the project, otherwise, you should specify the path of it. Ex: Write a program to reads student s information (full name, id, email, and mobile) from a file, and prints them to the console. Solution: Scanner input = new Scanner(new File("input.txt")); String name = input.nextline(); int id = input.nextint(); String email = input.next(); int mobile = input.nextint(); System.out.println(name); System.out.println(id); System.out.println(email); System.out.println(mobile); 8

Lab Work Ex1: Write a program that reads an English word and checks if it contains vowels (a, e, i, o, u). If so, output Contains vowels, else, output No vowels found. Solution: String word = input.nextline().tolowercase(); if (word.contains("a") word.contains("e") word.contains("i") word.contains("o") word.contains("u")) { System.out.println("Contains vowels"); } else { System.out.println("No vowels found"); } Ex2: Write a program to prompts the user to enter a simple equation with one operator (*, /, +, -, %), and two operands (decimal numbers) (Ex. 5 * 6.3 ), and outputs the result of the expression. Note that there can be more than one white space between operator and operands. Solution: Scanner input = new Scanner(System.in); String s = input.nextline().trim(); double d1 = Double.parseDouble(s.substring(0, s.indexof(' '))); double d2 = Double.parseDouble(s.substring(s.lastIndexOf(' ') + 1)); String op = s.substring(s.indexof(' '), s.lastindexof(' ')).trim(); double result = 0; switch (op) { case "*": result = d1 * d2; case "/": result = d1 / d2; case "+": result = d1 + d2; case "-": result = d1 - d2; case "%": result = d1 % d2; } System.out.println("Result: " + result); 9

Other Solution: Scanner input = new Scanner(System.in); double d1 = Double.parseDouble(input.next()); String op = input.next(); double d2 = Double.parseDouble(input.next()); double result = 0; switch (op) { case "*": result = d1 * d2; case "/": result = d1 / d2; case "+": result = d1 + d2; case "-": result = d1 - d2; case "%": result = d1 % d2; } System.out.println("Result: " + result); 10

Homework 1. Write an application that compares two strings input by the user. Output whether the first string is less than, equal to or greater than the second string. 2. Write an application that inputs a line of text and outputs the text twice. Once in all uppercase letters and once in all lowercase letters. Print the length of the text. The first character of the text. (don't forget to trim the text before using it). 3. Write a program that prompts the user to enter two strings and prints whether the second string is a substring of the first string. 4. Write a program to reads a logic equation from a file, and outputs the result of the equation to the console. The file should contain one equation with one operator (and, or, not). The operands must be (True, False). Here is a sample file: And here is the console output: Good Luck 11