Text User Interfaces. Keyboard IO plus

Similar documents
More sophisticated behaviour

Full file at

More Sophisticated Behaviour

ing execution. That way, new results can be computed each time the Class The Scanner

File I/O Array Basics For-each loop

A token is a sequence of characters not including any whitespace.

Simple Java Input/Output

Main loop structure. A Technical Support System. The exit condition. Main loop body

CITS1001 week 6 Libraries

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

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling 2

Fundamentals of Programming Data Types & Methods

4. Java Project Design, Input Methods

Using Java Classes Fall 2018 Margaret Reid-Miller

Java Input/Output. 11 April 2013 OSU CSE 1

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

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

AP Computer Science Unit 1. Writing Programs Using BlueJ

Reading Input from Text File

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

AP Computer Science Unit 1. Writing Programs Using BlueJ

CS 112 Introduction to Programming

Object-Oriented Programming in Java

Computational Expression

Reading Text Files. 1 Reading from text files: Scanner

CSCI 1103: File I/O, Scanner, PrintWriter

Section 2.2 Your First Program in Java: Printing a Line of Text

Example Program. public class ComputeArea {

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output

Introduction to Java Unit 1. Using BlueJ to Write Programs

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

CS 302: Introduction to Programming

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

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

CMSC131. Introduction to your Introduction to Java. Why Java?

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

Chapter 4 Classes in the Java Class Libraries

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

A Quick and Dirty Overview of Java and. Java Programming

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

Chapter 2: Data and Expressions

Chapter 4 Defining Classes I

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Chapter 2: Basic Elements of Java

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java

Full file at

CSCI 1103: File I/O, Scanner, PrintWriter

CP122 CS I. Chapter 11: File I/O and Exceptions

HST 952. Computing for Biomedical Scientists Lecture 8

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

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

Introduction to Java Applications; Input/Output and Operators

Introduction to Java (All the Basic Stuff)

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

COMP 202 Java in one week

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

Methods CSC 121 Fall 2016 Howard Rosenthal

Robots. Byron Weber Becker. chapter 6

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

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

Introduction to Java Applications

Object Oriented Programming. Java-Lecture 1

Chapter 2: Data and Expressions

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

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

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

Dining philosophers (cont)

Experiment No: Group B_4

Computer Science is...

CS 251 Intermediate Programming Java I/O Streams

Starting Out with Java: From Control Structures Through Objects Sixth Edition

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.

Simple Java Reference

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

Fall 2017 CISC124 10/1/2017

Programming with Java

Some miscellaneous concepts

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

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

CS Programming I: File Input / Output

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

File Processing. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. A Class for Representing a File

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

Methods CSC 121 Spring 2017 Howard Rosenthal

AP Computer Science Unit 1. Programs

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

H212 Introduction to Software Systems Honors

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

Lecture 8 " INPUT " Instructor: Craig Duckett

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Programming Assignment Comma Separated Values Reader Page 1

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

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2010) - All Sections Midterm Examination

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

Topic 11 Scanner object, conditional execution

DPCompSci.Java.1718.notebook April 29, 2018

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

First Java Program - Output to the Screen

CS 231 Data Structures and Algorithms, Fall 2016

Transcription:

Text User Interfaces Keyboard IO plus

User Interface and Model Model: objects that solve problem at hand. User interface: interacts with user getting input from user giving output to user reporting on status of model. Flexibility in design: identifying these as separate subsystems.

Writing standard output System.out: methods for writing to standard output. public void println (String s) Write specified String to standard output and then terminate the line. public void print (String s) Write the specified String to standard output. public void println () Terminate current line by writing line terminator to standard output. public void flush () Flush stream: write buffered output to standard output and flush that stream.

Java Input The Scanner Class A standard Java class We will use it to help with keyboard input Part of Java 5 onwards

import java.util.scanner; The import tells Java to look for Scanner methods A simple text scanner which parses primitive types and strings Uses a delimiter pattern of whitespace to identify tokens

Example Program 1 import java.util.scanner; public class ScannerEx1 { private Scanner myscanner; public ScannerEx1() { myscanner = new Scanner( System.in ); }

Explanation Program 1 // Tells Java to look for the Scanner class import java.util.scanner; // Declares a Scanner object called myscanner Scanner myscanner ; // Create a Scanner object called myscanner // will get input from the keyboard myscanner = new Scanner( System.in );

Example Program 1 cont public String getline(string prompt) { System.out.print( prompt); // nextline() is a method of the Scanner class // it reads a line of text from the keyboard. } return myscanner.nextline();

Some Scanner Methods To read this A number with no decimal point A number with a decimal point A word ending in a blank space A line ( or what remains of the line) A single character Use this nextint(); nextdouble(); next(); nextline(); findinline(. ).charat(0);

public int getint(string prompt) { System.out.print( prompt); return myscanner.nextint(); } public double getdouble(string prompt) { System.out.print( prompt); return myscanner.nextdouble(); }

public String getword(string prompt) { System.out.print( prompt); return myscanner.next(); } public char getchar(string prompt) { System.out.print( prompt); } return myscanner.findinline(".").charat(0);

More on Scanner If there are no tokens in the input stream, it will wait until user keys in a line with non-blank characters. An input stream can be closed with the command close(). If an input stream is closed or terminated attempting to read it will fail.

Yet more After reading some input tokens, you can skip the rest of the input tokens in the current line with the method public String nextline() advances past the current line and returns any input that was skipped excluding the line terminator.

More Scanner methods Have preconditions: token of form specified by method used, otherwise fails. To verify these preconditions use: hasnextboolean() hasnextint() hasnextdouble() hasnext()

Building a simple Text based UI A Fahrenheit to Centigrade Conversion Application The Specification: Allow user to input temperature in Fahrenheit and be told the Centigrade equivalent Allow user to do opposite, i.e Centigrade to Fahrenheit Program menu driven

Design Thoughts Need to identify classes a Fahrenheit class? a Centigrade class? why both? How to deal with I/O? Use separate class

FahrenheitTemperature Class What services should this class provide? default constructor : what initial value? get Temperature set Temperature get Centigrade equivalent

CentigradeTemperature Class What services should this class provide? default constructor : what initial value? get Temperature set Temperature get Fahrenheit equivalent

FahrenheitTemperature Class public class FahrenheitTemperature { private double ftemperature; // The Fahrenheit temperature public FahrenheitTemperature() { ftemperature = 32.0; // freezing point of water }

FahrenheitTemperature public double getftemperature() { return ftemperature; } Class public double converttocentigrade() { double centigrade; } centigrade = 5.0 * (ftemperature -32.0) / 9.0; return centigrade; public void setftemperature( double newftemperature) { ftemperature =newftemperature; }

CentigradeTemperature class Essentially similar to FahrenheitTemperature class Main difference in conversion formula: f = 9.0 * c / 5.0 +32.0 Coding left as an exercise

Text UI Class Will provide a menu with commands to: Convert from F to C Convert from C to F Quit the program What does the UI need to know? FahrenheitTemperature object CentigradeTemperature object Any thing else? Lets wait and see

Text UI Code public class TemperatureConversionUI { // attributes private CentigradeTemperature c ; private FahrenheitTemperature f ; private Scanner myscanner;

constructor public TemperatureConversionUI() { c = new CentigradeTemperature(); f = new FahrenheitTemperature (); myscanner = new Scanner(System.in);. }

Some thoughts on the menu Consider what it should look like Options are Convert from Fahrenheit to Centigrade enter 1 Convert from Centigrade to Fahrenheit enter 2 To end program enter 3 Enter command :

First attempt at Menu public void menu() { int command; displaymenu(); command = getcommand(); execute( command ); }

displaymenu private void displaymenu() { System.out.println( Options are ); System.out.println( Convert from Fahrenheit to Centigrade enter 1 ); System.out.println( Convert from Centigrade to Fahrenheit enter 2 ); System.out.println( To end program enter 3 ); }

getcommand() private int getcommand() { System.out.print ( Enter command: ); return myscanner.nextint(); }

execute() private void execute( int command) { if ( command == 1) doftoc(); else if ( command == 2 ) doctof(); else if ( command == 3) System.exit(0); else System.out.println( Unkown command ); }

doftoc() private void doftoc() { System.out.print( Enter F temperature: ); } double ft = myscanner.nextdouble(); f. setftemperature( ft); System.out.println( ft + F equals + f. converttocentigrade() + C );

doctof() private void doctof() { System.out.print( Enter C temperature: ); } double ct = myscanner.nextdouble(); c. setctemperature( ct); System.out.println( ct + C equals + c. convertto Fahrenheit() + F );

Review the design public void menu() { int command; displaymenu(); command = getcommand(); execute( command ); } Only allows for one command then program closes

Better method public void menu() { int command = 0; while ( command! = 3 ) { displaymenu(); command = getcommand(); execute( command ); } }

execute() - revised private void execute( int command) { if ( command == 1) doftoc(); else if ( command == 2 ) doctof(); else if ( command == 3) System.out.println( Program closing down ); else System.out.println( Unknown command ); }

Java Applications public static void main (String [ ] args)

Java applications To run a Java program the JVM needs to know which class to start with It looks for a class containing a method called main There should only be one such class Syntax public static void main (String [ ] args)

Example public class Example { } public static void main (String [ ] args) { // code goes here }

The main method main must exist main must be public main must be static (class method) main must have a String array parameter Only main can be invoked

Use of main Good OOP style requires that main be kept simple Guidelines: create an object call the first method Should NOT be full of complex logic!

Main method - example public static void main(string[] args) { TemperatureConversionUI textui = new TemperatureConversionUI() textui.menu(); }

Using main in BlueJ Create a new project called ExampleMain Create a class in the project called ExampleMain Type in the following code: (see next slide) Compile the class

public class ExampleMain { public static void main (String [] args) { System.out.println("Hello"); } }

Using main in BlueJ continued Select the class you will see the constructor listed (ignore) also main will be listed You can invoke main without instantiating an object

Summary A Java application will consist of several classes One and only one class will contain the main method The main method will just start the application going The main method will NOT contain any complex logic

Some of the plus For some applications it is necessary to save data to files and to get the data from a file This is called data persistence Can use the Scanner class to obtain data from a file

Using the Scanner to read a file import java.util.scanner; import java.io.*;.. public void ScannerFileRead( String filename) throws FileNotFoundException { String aline; Scanner discscanner = new Scanner( new File(fileName )); while ( discscanner.hasnext() ) { aline= discscanner.nextline(); System.out.println(aLine); } discscanner.close(); Can use the Scanner methods with the file, e.g. next(), nextint(), } }

Explanation throws FileNotFoundException The program expects that the file already exists If it does not it complains new File( filename) Java has a File class. Here we are telling the Scanner to link to the file discscanner.close(); Tell the system that the file is free

Output to a file import java.io.*; { public void PrintTextFile( String filename) throws IOException } PrintStream print = new PrintStream( new File( filename) ); print.println( "The world is so full" ); print.println( "Of a number of things," ); print.println( "I'm sure we should all" ); print.println( "Be as happy as kings." ); print.close();

Explanation If the file already exists its contents will be destroyed unless the user does not have permission to alter the file. If this is the case, an IOException will be thrown The program will end.

Side Notes: Some String operations Many operations for Strings See API documentation for class String Important one public boolean equals(object anobject) Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object

Side note: String equality if(input == "bye") { }... tests identity if(input.equals("bye")) { }... tests equality Strings should always be compared with.equals

Identity vs equality 1 Other (non-string) objects: :Person Fred :Person Jill person1 person2 person1 == person2?

Identity vs equality 2 Other (non-string) objects: :Person Fred :Person Fred person1 person2 person1 == person2?

Identity vs equality 3 Other (non-string) objects: :Person Fred :Person Fred person1 person2 person1 == person2?

Identity vs equality (Strings) String input = reader.getinput(); if(input == "bye") {... } == tests identity :String "bye" :String ==? "bye" input (may be) false!

Identity vs equality (Strings) String input = reader.getinput(); if(input.equals("bye")) {... } equals tests equality :String "bye" :String equals? "bye" input true!

Class Variables Classes can have fields Known as Class variables or static variables Exactly one copy of a class variable exists Shared by all instances Syntax: private static type variablename; private static int count;

Constants Can declare constants using key word final e.g. final int GRAVITY = 3; convention: constants are ALL CAPITALS

example // effect of gravity private static final int GRAVITY = 3; here we have a class constant no matter how many instances are created only one GRAVITY will exist

Class variables

The Java class library Thousands of classes Tens of thousands of methods Many useful classes that make life much easier A competent Java programmer must be able to work with the libraries.

Working with the library You should: know some important classes by name; know how to find out about other classes. Remember: We only need to know the interface, not the implementation.

Reading class documentation Documentation of the Java libraries in HTML format; Readable in a web browser Class API: Application Programmers Interface Interface description for all library classes

Interface vs implementation The documentation includes the name of the class; a general description of the class; a list of constructors and methods return values and parameters for constructors and methods a description of the purpose of each constructor and method the interface of the class

Interface vs implementation The documentation does not include private fields (most fields are private) private methods the bodies (source code) for each method the implementation of the class

Using library classes Classes from the library must be imported using an import statement (except classes from java.lang). They can then be used like classes from the current project.

Packages and import Classes are organised in packages. Single classes may be imported: import java.util.arraylist; Whole packages can be imported: import java.util.*;

Writing class documentation Your own classes should be documented the same way library classes are. Other people should be able to use your class without reading the implementation. Make your class a 'library class'!

Elements of documentation Documentation for a class should include: the class name a comment describing the overall purpose and characteristics of the class a version number the authors names documentation for each constructor and each method

Elements of documentation The documentation for each constructor and method should include: the name of the method the return type the parameter names and types a description of the purpose and function of the method a description of each parameter a description of the value returned

javadoc Class comment: /** * The Responder class represents a response * generator object. It is used to generate * an automatic response. * * @author Michael Kölling * @version 1.0 (30.Mar.2006) */

javadoc Method comment: /** * Read a line of text from standard input (the text * terminal), and return it as a set of words. * * @param prompt A prompt to print to screen. * @return A set of Strings, where each String is * one of the words typed by the user */ public HashSet<String> getinput(string prompt) {... }

Public vs private Public attributes (fields, constructors, methods) are accessible to other classes. Fields should not be public. Private attributes are accessible only within the same class. Only methods that are intended for other classes should be public.

Information hiding Data belonging to one object is hidden from other objects. Know what an object can do, not how it does it. Information hiding increases the level of independence. Independence of modules is important for large systems and maintenance.