Você está na página 1de 4

Exercise Solutions

n
Palindrome Solutions
n Palindrome

COMP209 n Word & letter • Using StringBuffer:


count
Object Oriented Programming
n Formatting
Utility Classes 2 Numbers
public class Palindrome1 {

public static void main (String args []) {


n Locales StringBuffer s = new StringBuffer (args[0]);
StringBuffer t = new StringBuffer (args[0]);
Mark Hall n Factory Design if (s.toString().equals(t.reverse().toString())) {
Pattern System.out.println(s+" is a palindrome");
} else {
n System System.out.println(s+" is not a palindrome");
}
n Runtime
}
n Singleton }

Department of Computer Science


Design Pattern
1 Department of Computer Science 2

Palindrome Solutions Computing word counts and letter frequencies


public void process(BufferedReader r) throws IOException {
• Using String: String delims =
" \t\n.,!?;:[]{}()%$^&@#></\"\'-_+=`~1234567890";
int lines = 0; int words = 0; int letters = 0;
public class Palindrome2 { int [] letterFreq = new int [26];
String line;
public static void main (String args []) {
String s = args[0]; while ((line = r.readLine()) != null) {
for (int i=0; i<s.length()/2; i++) { line = line.toLowerCase(); lines++;
if (!(s.charAt(i) == (s.charAt(s.length()-1-i)))) { StringTokenizer tok =
System.out.println(s+" is not a palindrome"); new StringTokenizer(line, delims);
return; while (tok.hasMoreTokens()) {
} String next = tok.nextToken();
} words++; letters += next.length();
System.out.println(s+" is a palindrome"); for (int i = 0; i < next.length(); i++) {
} letterFreq[next.charAt(i) - 'a']++;
} }
}
}
Department of Computer Science 3
// continued on next slide

Computing word counts and letter


frequencies Formatting Numbers
• Example output from the above program:
// continued from previous slide
Num letters: 1314 Num words: 262 Num lines: 37
System.out.println("Num letters: " + letters
a: 0.0745814307458143
+ " Num words: " + words
b: 0.01293759512937595
+ " Num lines: " + lines);
c: 0.0380517503805175
for (int i = 0; i < 26; i++) {
d: 0.0289193302891933
System.out.println((char)(i + 'a') + ": "
e: 0.0989345509893455
+ ((double)letterFreq[i] / letters));
. . .
}
} • 16 decimal places is probably overkill :-)
• What if we wanted to output percentages to one
decimal place?
Department of Computer Science 5 Department of Computer Science 6

Department of Computer Science 1


Formatting Numbers
• We can make use of java.text.NumberFormat NumberFormat
to format numbers for us
NumberFormat pf = NumberFormat.getPercentInstance();
pf.setMaximumFractionDigits(1); • Abstract base class
for (int i = 0; i < 26; i++) {
System.out.println((char)(i + 'a') + ": " • Provides a number of static creation methods
+ pf.format(((double)letterFreq[i]
/ letters)));
that return various concrete sub classes
} – Numbers, percentages, currencies
– Locale sensitive
Num letters: 1314 Num words: 262 Num lines: 37
a: 7.5% • Has methods for setting min/max fraction and
b: 1.3%
c: 3.8%
integer digits, parsing numbers etc.
d: 2.9%
e: 9.9%
Department of Computer Science 8

NumberFormat NumberFormat
• In the previous example we used the default • We can find out what locales NumberFormat
locale for formatting the percentages supports by calling the static
• Can also specify a locale getAvailableLocales method
NumberFormat pf = – Returns an array of java.util.Locale objects
NumberFormat.getPercentInstance(Locale.GERMAN); • Locale encapsulates information about a
region—language and country
Num letters: 1314 Num words: 262 Num lines: 37
a: 7,5% • Construct with ISO standard two or three character country
b: 1,3% and language codes
c: 3,8% • Has some static constants for various countries and
d: 2,9% languages
e: 9,9%
. . .
Department of Computer Science 9 Department of Computer Science 10

Abstract Factory/Factory Method


LocaleTest Design Pattern
• Prints out locales supported by NumberFormat • NumberFormat takes advantage of a variation of the
Locale [] l = NumberFormat.getAvailableLocales(); Abstract Factory (and closely related Factory Method)
for (int i = 0; i < l.length; i++) {
System.out.println(l[i]); design pattern
} • Basic idea is to provide a mechanism for creating
. . . instances of related objects without specifying their
en_AU concrete representations
en_CA
en_GB – Completely decouple clients from concrete types—instead
en_IE objects are manipulated polymorphically through a common
en_IN interface or parent class
en_NZ
en_ZA
. . . Department of Computer Science 12

Department of Computer Science 2


Abstract Factory/Factory Method Abstract Factory/Factory Method
Design Pattern Design Pattern
• NumberFormat’s static creation methods are • NumberFormat has two types of factory
factory methods methods
– They return concrete implementations characterized – Default factory methods —
only by the NumberFormat interface getPercentInstance(),
• The factory method’s job is to select the getNumberInstance(), etc
• return NumberFormat objects for the default locale
appropriate concrete implementation
– Parameterized factory methods —
• Clients do not need to know what concrete getPercentInstance(Locale l), …
implementation they are using • return differently configured NumberFormat objects
depending on which locale is supplied
Department of Computer Science 13 Department of Computer Science 14

Abstract Factory/Factory Method


Design Pattern java.lang.System
• Abstract Factory is often used to implement UI toolkits
that support different look-and-feel standards, Eg: • Provides access to a number of systemwide resources
– Streams for standard in, out and error — System.in,
– Have an abstract WidgetFactory class that defines factory
System.out, System.err
methods for creating different widgets (buttons, scroll bars etc).
• Static methods to reassign in, out and err
Also have abstract classes for each kind of widget
– Static method exit(int status) — halt the currently
– Have concrete subclasses of WidgetFactory that supply
concrete widgets for different look-and-feels running program
– Static method currentTimeMillis — returns the
– Could also have a static factory method in the WidgetFactory
current time in milliseconds since Jan 1, 1970
class to return various concrete subclasses
– Static method gc — force the garbage collector to run
• Java’s Toolkit (awt) class takes this approach to link
– arraycopy — fast static method that is overloaded to
widget abstractions to platform dependent UI elements handle copying arrays of all types
Department of Computer Science 16

java.lang.Runtime
Java.lang.System • Runtime allows a Java application to interact with
environment in which the application is running
• System.arraycopy • Can’t construct a Runtime object
– Obtain a Runtime object by calling the static method
– Takes a source array, source position, getRuntime()
destination array, destination position and
length • Some methods:
– int availableProcessors() — # processors
– Throws available to the virtual machine
• IndexOutOfBoundsException if accessing outside of – long freeMemory() — amount of free memory
either source or destination array’s bounds available to the virtual machine
• ArrayStoreException if there is a type mismatch – long maxMemory() — maximum amount of memory
between source and distination arrays that the vitual machine will attempt to use
• NullPointerException if either array is null
Department of Computer Science 17 Department of Computer Science 18

Department of Computer Science 3


java.lang.Runtime java.lang.Runtime
• Some more methods:
– Process exec(String cmd)
• The exec processes in Runtime create a native process
• Execute named command in a separate process
and return an instance of a concrete subclass of
– Process exec(String cmd, String [] envp) Process
• Execute named command with supplied environment settings in a – Another example of a factory method
separate process • The created subprocess does not have its own console
– Process exec(String cmd, or terminal
String [] envp, File dir) – As a consequence, we can’t use redirection of in/out in the
• Execute named command with supplied environment settings and command to be executed (e.g. can’t do “ls -l > blah.txt”)
working directory in a separate process
– Process provides access to input and output stream objects
• cmd gets parsed using a StringTokenizer that can be used to read and write to/from the subprocess
• Each element of envp is an environment variable • Process also provides methods to wait for the
setting with format name=value subprocess to complete and to kill the subprocess
Department of Computer Science 19 Department of Computer Science 20

Using Runtime to execute a


system command Singleton Design Pattern
try {
Runtime r = Runtime.getRuntime(); // get runtime object • Sometimes we only ever need a single instance of a
Process p = r.exec("ls -l"); //exec ls cmd under linux
InputStream is = p.getInputStream(); class
BufferedReader br = • Runtime is an example of the Singleton design pattern
new BufferedReader(new InputStreamReader(is));
String next; • The intent of the Singleton pattern is to ensure that a
// Read the output of the system process class has only one instance, and to provide a global
while ((next = br.readLine()) != null) { point of access to it
System.out.println(next);
} – A java class can make use of a private constructor to prevent
} catch (Exception ex) { clients from instantiating objects of the class
ex.printStackTrace(); • Only one Runtime object is ever needed in order to
}
provide an application access to systemwide resources
Department of Computer Science 22

Singleton Design Pattern Readings


• Primary benefits of the Singleton design pattern
– Controlled access to sole instance—the Singleton class has
• Budd, chapter 17
strict control over how and when clients access the sole • Budd, section 15.6 and 15.7
instance. Ensures that no other instances can be created
– Reduced name space—the Singleton pattern is a better
• Javadocs for NumberFormat, Locale,
solution than using global variables to store sole instances System, Runtime and Process
– Permits a variable number of instances—the pattern makes it
easy to change your mind and allow more than one instance of
the Singleton class
• Same approach can be used to control the number of instances that the
application uses; only the operation that grants access needs to change

Department of Computer Science 23 Department of Computer Science 24

Department of Computer Science 4

Você também pode gostar