COMP206-08S General Programming 2 Geoff Holmes and Bernhard Pfahringer Lectures - Today Random Numbers Timing Assignment 1 Review Department of Computer Science 2 Random Numbers import java.util.Random; Implements a random number generator that appears to generate random numbers Construct object of Random class Use methods nextInt(n) – random number 0 -> n-1 nextDouble() – random number 0 -> 1 (exclusive) Constructors use system clock – no params or you can “seed” the generator Department of Computer Science 3 Example Random generator = new Random( ); int oneToTen = 1 + generator.nextInt(10); Department of Computer Science 4 Useful utility import java.util.Random; public class ArrayUtil { private static Random generator = new Random(); public static int[] randomIntArray(int length, int n) { int[] a = new int[length]; for(int i=0; i<a.length; i++) a[i] = generator.nextInt(n); return a; } public static void print(int[] a) { for (int x : a) System.out.print(x + " "); System.out.println(); } } Department of Computer Science 5 Test for Array Util public class TestArrayUtil { public static void main(String[] args) { // 20 numbers in range 0 -> 99 int a[] = ArrayUtil.randomIntArray(20, 100); ArrayUtil.print(a); } } Department of Computer Science 6 Timing program runs Want to be able to assess how long something takes to run Can be complicated due to threads We will make use of a system call System.currentTimeMillis() This provides the current time in milliseconds so we need to do some work to convert to the elapsed time of the thing we are assessing. Can get elapsed time while running Department of Computer Science 7 Stop Watch Class public class StopWatch { private Boolean isRunning; private long startTime, elapsedTime; public StopWatch() { reset(); } public void start() { if (isRunning) return; isRunning = true; startTime = System.currentTimeMillis(); } Department of Computer Science 8 public void stop() { if (!isRunning) return; isRunning = false; long endTime = System.currentTimeMillis(); elapsedTime = elapsedTime + endTime - startTime; } public long getElapsedTime() { if (isRunning) { long endTime = System.currentTimeMillis(); return elapsedTime + endTime - startTime; } else return elapsedTime; } public void reset() { elapsedTime = 0; isRunning = false; } } Department of Computer Science 9 Test program for StopWatch public class TestStopWatch { public static void main(String[] args) { StopWatch timer = new StopWatch(); timer.start(); try { Thread.sleep(6000); } catch (InterruptedException exception) { } timer.stop(); System.out.println("Time to sleep ="+timer.getElapsedTime()); } } Department of Computer Science 10 Assignment 1 Review Java naming conventions All variables start with a lowercase letter and new words start with an uppercase letter Eg int num, int numFound Class names uppercase letter first (then as above) Eg Circle, Student, BinarySearchTree Method names as per variables Eg processFile, main, findOutliers Department of Computer Science 11 Question 1 – check chars public class palindrome { public static void main (String [] args) { String s = args[0]; for (int i=0; i<s.length()/2; i++) { if (!(s.charAt(i) == (s.charAt(s.length()-1-i)))) { System.out.println(s+" is not a palindrome"); return; } } System.out.println(s+" is a palindrome"); } } Department of Computer Science 12 Question 1 – use String methods public static void main (String[ ] args) { StringBuffer s = new StringBuffer (args[0]); StringBuffer t = new StringBuffer (args[0]); if (s.toString().equals(t.reverse().toString())) System.out.println(s+" is a palindrome"); else System.out.println(s+" is not a palindrome"); } Department of Computer Science 13 Complex Numbers public class Complex { private float real; private float imag; public Complex(float r, float i) { real = r; imag = i; } public Complex() { real = 0; imag = 0; } Department of Computer Science 14 public Complex add(Complex a) { Complex result = new Complex(); result.real = a.real + this.real; result.imag = a.imag + this.imag; return result; } public String toString() { String result = new String(); result = "Real part = " + this.real; result += " Imag part = " + this.imag; return result; } public boolean equals (Complex y) { boolean result; result = (this.real == y.real && this.imag == y.imag); return result; } } Department of Computer Science 15 equals The equals method can be either overloaded or overridden Here it is overloaded – so there are two equals methods boolean equals(Complex other) – defined in Complex boolean equals(Object other) – defined in Object boolean equals(Complex x, Complex y) is a different method entirely Department of Computer Science 16 Equals – formal defn public boolean equals(Object otherObject) { if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; Complex other = (Complex) otherObject; return (this.real == other.real && this.imag == other.imag); } Department of Computer Science 17 Question 3 - Scanner import java.util.Scanner; public class TestComplex { public static void main (String [] args) { Scanner in = new Scanner(System.in); int xr = in.nextInt(); int xi = in.nextInt(); Complex x = new Complex(xr,xi); String op = in.next(); int yr = in.nextInt(); int yi = in.nextInt(); Complex y = new Complex(yr, yi); Complex result; if (op.equals("+")) { result = x.add(y); System.out.println("result is "+result.toString()); } else System.out.println("Something went wrong"); } } Department of Computer Science 18 Scanner methods Scanner(InputStream in) Scanner(Reader in) boolean hasNext() String next() int nextInt() String nextLine() Department of Computer Science 19 One line input import java.util.Scanner; import java.util.StringTokenizer; public class TestComplex { public static void main (String [] args) { Scanner in = new Scanner(System.in); String s = in.nextLine(); StringTokenizer tokens = new StringTokenizer(s); String openBracket = tokens.nextToken(); int xr = Integer.parseInt(tokens.nextToken()); int xi = Integer.parseInt(tokens.nextToken()); Complex x = new Complex(xr, xi); String op = tokens.nextToken(); int yr = Integer.parseInt(tokens.nextToken()); int yi = Integer.parseInt(tokens.nextToken()); Complex y = new Complex(yr, yi); String closeBracket = tokens.nextToken(); Complex result; if (op.equals("+")) { result = x.add(y); System.out.println("result is "+result.toString()); } else System.out.println("Something went wrong"); } } Department of Computer Science 20 Question 4 import java.util.ArrayList; public class TestShapes { public static void main(String[] args) { ArrayList<Shape> shapes = new ArrayList<Shape>(); shapes.add(new Circle(4)); shapes.add(new Triangle(5,10)); shapes.add(new Rectangle(4,5)); double totalArea = 0; for (Shape x : shapes) { totalArea += x.area(); } System.out.println("Total area is "+totalArea); } } Department of Computer Science 21 Implement Shape as an Interface public interface Shape { double area(); } Department of Computer Science 22 And each shape implements area public class Circle implements Shape { private double radius; public Circle() { radius = 0; } public Circle(double r) { radius = r; } public double area() { return Math.PI*radius*radius; } } Department of Computer Science 23 Similarly for others public class Rectangle implements Shape { private double width, length; public Rectangle() { width = 0; length = 0; } public Rectangle(double w, double l) { width = w; length = l; } public double area() { return width*length; } } Department of Computer Science 24 And Triangle public class Triangle implements Shape { private double base, height; public Triangle() { base = 0; height = 0; } public Triangle(double b, double h) { base = b; height = h; } public double area() { return 0.5*base*height; } } Department of Computer Science 25