Today s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO. Understanding Board

Similar documents
Today s plan Discuss the Lab 1 Show Lab 2 Review basic Java materials Java API Strings Java IO

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

IT101. File Input and Output

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

Lecture 22. Java Input/Output (I/O) Streams. Dr. Martin O Connor CA166

CS 251 Intermediate Programming Java I/O Streams

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

Chapter 5 Some useful classes

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Classes Basic Overview

Simple Java Input/Output

This Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java.

Introduction Unit 4: Input, output and exceptions

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

Installing Java. Tradition. DP Computer Science Unit 4.3: Intro to programming 1/17/2018. Software & websites

CSE 21 Intro to Computing II. JAVA Objects: String & Scanner

HST 952. Computing for Biomedical Scientists Lecture 8

Remedial Java - io 8/09/16. (remedial) Java. I/O. Anastasia Bezerianos 1

Object Oriented Software Design

Object Oriented Software Design

1.00 Lecture 30. Sending information to a Java program

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

Full file at

Object-Oriented Programming Design. Topic : Streams and Files

Java Input/Output. 11 April 2013 OSU CSE 1

Objec&ves. Review. Standard Error Streams

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

Software 1 with Java. Recitation No. 7 (Java IO) May 29,

Lecture 11.1 I/O Streams

Lecture Set 2: Starting Java

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

Lecture Set 2: Starting Java

ECE 122 Engineering Problem Solving with Java

String related classes

Fall 2017 CISC124 10/1/2017

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

Software 1. Java I/O

Software 1 with Java. Recitation No. 9 (Java IO) December 10,

Core Java Contents. Duration: 25 Hours (1 Month)

PIC 20A Streams and I/O

CS 106A Midterm Review. Rishi Bedi, adapted from slides by Kate Rydberg and Nick Troccoli Summer 2017

Core Java Syllabus. Overview

AP Computer Science A

USING LIBRARY CLASSES

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

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

Exceptions and Working with Files

Overview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

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

File I/O Introduction to File I/O Text Files The File Class Binary Files 614

Dining philosophers (cont)

Eng. Mohammed Abdualal

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

Introduction to Programming Using Java (98-388)

Byte and Character Streams. Reading and Writing Console input and output

WOSO Source Code (Java)

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

Streams and File I/O

Lab 5: Java IO 12:00 PM, Feb 21, 2018

More on Java. Object-Oriented Programming

DM550 Introduction to Programming part 2. Jan Baumbach.

COMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

Contents Chapter 1 Introduction to Programming and the Java Language

COMP 110 Introduction to Programming. What did we discuss?

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

Chapter 2: Data and Expressions

Active Learning: Streams

File Input/Output. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Software 1 with Java. The java.io package. Streams. Streams. Streams. InputStreams

Case Study: Savings Account Interest

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

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

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

COMP String and Console I/O. Yi Hong May 18, 2015

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

Getting started with Java

CSE 21 Intro to Computing II. Post-Midterm Review

Course Content. Objectives of Lecture 22 File Input/Output. Outline of Lecture 22. CMPUT 102: File Input/Output Dr. Osmar R.

Programming Languages and Techniques (CIS120)

First Java Program - Output to the Screen

Experiment No: Group B_4

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

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

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

COMP6700/2140 Std. Lib., I/O

COMP-202 More Complex OOP

תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת

Chapter 4 Java I/O. X i a n g Z h a n g j a v a c o s q q. c o m

Program Elements -- Introduction

Transcription:

Ananda Gunawardena Today s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO Lab 1 Objectives Learn how to structure TicTacToeprogram as an object oriented programming assignment. Understanding Board 0 1 1 0 2 0 0 0 0 Engine What does win means? if (board[0][0] == player && board [0][1] == player && board [0][2] == player) return true Driver Player Behaviors Player 1 or 2 setplayer Sets the internal value of to player Java Application Programmer interface (API) getmove Move object with row, col, player 1

Java APIs classes interfaces Abstract classes Packages Java API Java APIs Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs Download APIs to your local computer from http://java.oracle.com/j2se/1.5/download.html Treat it as a dictionary for reference, instead of a book from front to back Strings a b b c d String Methods Examples Construct a string String s = "Hello world"; Get the length of the string int length = s.length();//length = 11 Access a part of the string String sub = s.substring(6);//"world" char c = s.charat(1); //'e' Concatenate strings String t = " of java"; String s1 = s + t; //"Hello world of java Covert Character c to String Character.toString(c); Do a search Java String API to find all of the methods String is immutable. Once created, it cannot be changed. There is no such a method setchar(char c) Why? Security reasons. (The detailed explanation is complicated and not useful in this course. Doing the following exercises is more helpful in understanding the concept.) Q: What are the values of chararray1 and chararray1 at the end of the code char[] chararray1 = {'a', 'b', 'c'; char[] chararray2 = chararray1; chararray1[1] = 'i'; //chararray1 = {'a', i', 'c' //chararray1 = {'a', i', 'c' 2

Q: What are the values of s1 and s2 at the end of the code String s1 = "abc"; String s2 = s1 ; s1 = s1 + "def"; // s1 = "abcdef" //s2 = "abc" String Main Usage Comparing strings Q: Are word and work equal? Which is bigger? String s1 = "word"; String s2 = "work"; System.out.println(s1.equals(s2)); //false System.out.println(s1.compareTo(s2)); // -3, meaning "word < "work" // two strings are compared lexicographically. The result is a negative integer if this s1 lexicographically precedes s2. The result is a positive integer if s1 lexicographically follows s1. The result is zero if the strings are equal; String Main Usage Check if two strings have the same prefix and postfix Does hello world starts with hell? String s = "hello world"; System.out.println(s.startsWith("hell"));//true System.out.println(s.endsWith("world"));//true Convert cases I want to turn hello world into upper cases. String supper = s.touppercase();//"hello WORLD" String Main Usage Finding the index of a substring I want to know the position of o sin the string String s = "Hello world"; s.indexof("o");//4, return -1 if the argument string not found s.lastindexof("o");//7 String main usage Special characters String Advanced Usage breaking words apart Use \ to proceed the special characters Tab \t New line \n Carriage return \r Single quote \ Double quote \ Backslash \\ Q: What is output of the strings? System.out.println("a\nb\tc ); //a //b c Q: How do you represent the file path c:\data\file.txt? String filepath = c://data//file.txt Q: I want to break "Hello world of java into "Hello world of java String s = "Hello world of java"; StringTokenizer st = new StringTokenizer(s); while (st.hasmoretokens()) { System.out.println(st.nextToken()); //Hello //world //of //java 3

String Advanced Usage breaking words apart Q: I want to break "Hello, world of java into "Hello world of java (this is a comma in the string) String s = "Hello, world of java"; StringTokenizer st = new StringTokenizer(s); while (st.hasmoretokens()) { System.out.println(st.nextToken()); //Hello, //world //of //java String Advanced Usage breaking words apart Q: I want to break "Hello, world of java into "Hello world of java String s = "Hello, world of java"; StringTokenizer st = new StringTokenizer(s, ", "); //, is the delimiter. Notice we need to supply all the possible delimiters in the string., and a space while (st.hasmoretokens()) { System.out.println(st.nextToken()); Hello world of java String Advanced Usage Concatenate strings repetitively Q: Suppose you have a list of 100 strings. You want to concatenate them into one string? Solution 1 List stringlist = new ArrayList(); for (int i = 0; i < 10; i++) { stringlist.add("string" + i); String finalstring = ""; for (Iterator iter = stringlist.iterator(); iter.hasnext(); ) { String s = (String) iter.next(); finalstring += s; //work but inefficient for large strings and large amount of concatenation because String is immutable. Intuitively, Java needs to maintain an a old string, a new string, and a concatenate string in each iteration. String Advanced Usage Concatenate strings repetitively Q: Suppose you have a list of 100 strings. You want to concatenate them into one string? Solution 2 List stringlist = new ArrayList(); for (int i = 0; i < 10; i++) { stringlist.add("string" + i); StringBuffer sb = new StringBuffer(); for (Iterator iter = stringlist.iterator(); iter.hasnext(); ) { String s = (String) iter.next(); sb.append(s); String Advanced Usage Strings and OOP I have just written a class. How can I represent the class with a string? public class Point { double x; double y; Point(double x, double y) { this.x = x; this.y = y; Point p = new Point(2,3); System.out.println(p); //Point@360be0 String Advanced Usage String and OOP I have just written a class. How can I represent the class with a string? Overwrite tostring() public class Point { double x; double y; Point(double x, double y) { this.x = x; this.y = y; public String tostring() { return "x = " + x + ", y = " + y; Point p = new Point(2,3); System.out.println(p); //x = 2.0, y = 3.0 4

String Advanced Usage Convert between strings to primitives Q: I want to convert an integer 123 to a string and convert a string 123 to an integer int i = 123; String s = i + ; String t = String.valueOf(i); String u = Integer.toString(i); //s = t = u = 123 Java IO int j = Integer.parseInt(s); // j = 123 //Extension Double.parseDouble(); Java IO Most programs need to interact with the outside world by reading and writing files from/to a hard disk Microsoft Office Matlab Eclipse Your future programs Java provides a comprehensive package to deal with file input and output. Java 5 Scanner Class java.util Class Scanner How to read an integer from stdin Scanner sc = new Scanner(System.in); int i = sc.nextint(); How to read a set of long integers from a file Scanner sc = new Scanner(new FileReader("file.txt")); while (sc.hasnextlong()) { System.out.println(sc.nextLong()); Scanner How to read a set of strings(words) from a file Scanner sc = new Scanner(new FileReader("file.txt")); while (sc.hasnext()) { System.out.println(sc.next()); Scanner Some useful scanner methods boolean hasnext() Returns true if this scanner has another token in its input. boolean hasnext(string pattern) Returns true if the next token matches the pattern constructed from the specified string. boolean hasnextdouble() Returns true if the next token in this scanner's input can be interpreted as a double value using the nextdouble() method. 5

STDOUT Other IO methods Q: How do I output something to the screen? To give user the result, or debug the code By using System.out.println() Object anobject = new Object(); String myanswer = "no"; int i = 42; System.out.println("Hello, World of Java"); System.out.println("An object is " + anobject); System.out.println("The answer is " + myanswer + " at this time."); System.out.println("The answer is " + i + '.'); //Hello, World of Java //An object is java.lang.object@18d107f //The answer is no at this time. //The answer is 42. STDIN How do I read input from the keyboard? To get input from the user from a consol instead of a GUI int b = 0; try { b = System.in.read();//returns an integer catch (Exception e) { System.out.println("Caught " + e); System.out.println("Read this data: " + (char)b); STDIN Using Scanner class Scanner Sc = new Scanner(System.in); Sc.nextInt(); or Sc.next(); // Read this data: 1 (after I typed 1) // Read this data: 1 (after I typed 123) // Read this data: a (after I typed a) //This gives you the ability to read one byte at a time. Java IO There are two kinds of files Files of characters (texts) Files of bytes (primitives, arrays, objects) java.io package contains Character streams Input Reader BufferedReader InputStreamReader FileReader Byte streams InputStream Output Writer BufferedWriter FileWriter PrintWriter OutputStream PrintStream Summary Java API is a dictionary of the Java language, and the interface for programmers to manipulate Java classes as black boxes. String is a class, and immutable. Construct a string String s = "Hello world"; Get its length s.length(); Get a substring s.substring(6) Concatenate strings s + t or StringBuffer Compare strings s1.equals(s2), s1.compareto(s2) s.startswith("hell"), s.endswith("world") Convert cases s.touppercase(); Finding the index of a substring s.indexof("o") Break a string apart StringTokenizer st = new StringTokenizer(s); Convert a string to primitives Integer.parseInt(s); Convert a primitive to a string 4+ Abstract classes are shown in italics. 6

Summary Data can be in the form of characters or bytes. IO is comprehensive Output a message to screen System.out.println("Hello, World of Java"); Output text data to a file PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("c://output.txt"))); Read an integer from the consol int b = System.in.read(); Read a line from the consol BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); or use Scanner class Read a file BufferedReader is = new BufferedReader(new FileReader("c://data.txt")); Or use Scanner class 7