CSC297.Java 2003F, Class 9: Arrays Admin: * I was thinking of diverging from Mr. Bishop's syllabus, but decided not to (yet). * I'd be interested in seeing your Rational classes. * Let's look at Mr. Bishop's assignment and decide what we need to add to ours. Overview: * What is an array? (What is a vector in Scheme?) * Scheme vectors vs. Java one-dimensional arrays * Java arrays vs. Java vectors Some notes on Rational numbers A nice way to create a "whole rational number" public Rational(long num) { this.numerator = num; this.denominator = 1; } // Rational(long) A more interesting problem: Convert a real to a rational. * Template public Rational(float num) { } // Rational(float) * Strategy one: Use simplify. Won't work. * Strategy two: Repeatedly multiply by 2 until no fractional part. double n = num; long d = 1; // As long as there is a fractional part while (n - Math.floor(n) > 0) { // Increment both n and d by the same factor n = n * 2; d = d * 2; } this.numerator = (long) n; this.denominator = d; this.simplify(); * Some morals: * For lots of similar tests, write a helper function * Think about a variety of cases * Since computers think in base two, your algorithms should, too /On to Bishop's stuff/ * Zero-parameter constructor. Easy. * String-based constructor. * Look at the String class. Helpful methods? * indexOf(ch) finds the position of the / * substring(int beginIndex, int endIndex) extracts numbers * substring(int beginIndex) also helps public Rational(String str) { int pos = str.indexOf('/'); this.numerator = str.substring(0, pos-1); this.denominator = str.substring(pos+1); this.simplify(); } // Rational(String)