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.