import java.awt.Color; import java.text.NumberFormat; import javax.swing.JOptionPane; import uwcse.graphics.GWindow; import uwcse.graphics.Oval; import uwcse.graphics.Rectangle; import uwcse.io.Input; public class PracticeWithLoops { public static void main(String[] args) { // interestCalculator(); // figureOfStars(); // sum35(); displayMandelbrotSet(); } /** * Displays a triangle of stars */ public static void figureOfStars() { Input in = new Input(); int lines; do { lines = in.readInt("Number of lines (or 0 to stop): "); for (int j = 1; j <= lines; j++) { // a line of lines - j spaces for (int i = 1; i <= lines - j; i++) { System.out.print(" "); } // a line of j stars for (int i = 1; i <= j; i++) { System.out.print("*"); } System.out.println(); } } while (lines != 0); // 0 is the sentinel value } /** * Number of years needed to double a money amount given an interest rate */ public static void interestCalculator() { Input in = new Input(); NumberFormat nf = NumberFormat.getCurrencyInstance(); char answer; do { // read the interest rate double rate = in .readDouble("Enter the interest rate (as a percentage): "); // compute the number of years double amount = 1000; int year = 0; while (amount <= 2000) { amount *= 1 + rate / 100; year++; } System.out.println("Number of years = " + year); System.out.println("Amount = " + nf.format(amount)); answer = in.readChar("Again (y or n)? "); } while (answer == 'y'); } /** * Sums all of the natural numbers below 1000 that are multiple of 5 or 3 */ public static void sum35() { int sum = 0; for (int i = 3; i < 1000; i++) { if (i % 3 == 0 || i % 5 == 0) { sum += i; } } System.out.println("Sum = " + sum); } public static void displayMandelbrotSet() { GWindow w = new GWindow(); w.setExitOnClose(); double xmin = -1.5; double xmax = 0.5; double ymin = -1; double ymax = +1; for (int i = 0; i < w.getWindowWidth(); i++) { for (int j = 0; j < w.getWindowHeight(); j++) { double x = xmin + (xmax - xmin) * i / w.getWindowWidth(); double y = ymax - (ymax - ymin) * j / w.getWindowHeight(); Color c = getMandelbrotColor(x, y); Rectangle o = new Rectangle(i, j, 1, 1, c, true); w.add(o); } w.doRepaint(); } } public static Color getMandelbrotColor(double x, double y) { double x0 = 0, y0 = 0; double x1, y1; int count = 0; do { x1 = x0 * x0 - y0 * y0 + x; y1 = 2 * x0 * y0 + y; x0 = x1; y0 = y1; count++; } while (count < 256 && x1 * x1 + y1 * y1 < 4); if (count > 240) { return Color.BLACK; } else if (count < 20) { return Color.BLUE; } else { int red = 255 - count; int green = 255 - count; int blue = 255 - count; return new Color(red, green, blue); } } }