Professor I.  Rudowsky                                                                                    CIS 26 MW12

Homework Assignment 2                                                                 Due Sep 20, 2004

 

Write a Java application that will produce a diamond pattern based on an odd integer number entered from a console prompt.  Do this once using the console for I/O and once using dialog boxes for I/O. Rather than print each line one at a time, create a String variable myDiamond and concatenate each row of the output string as it is generated. Be sure to include \n to indicate when a new line is required. When done, print myDiamond either to the console or as the output to a dialog box.  Write one application and each time ask the user if the I/O is console or dialog.

 

3 produces:

 

*

***

*

 

5 produces:

 

*

***

*****

***

*

7 produces:

*

***

*****

*******

*****

***

*

 

9 produces:

*

***

*****

*******

*********

*******

*****

***

*

In a loop, you will prompt for a positive, odd integer input. A value of 0 will end the application.

 

If the value entered is even, display a message that the number must be odd. Prompt for another number.

 

If the value is odd but less than 0 or greater than 17 display a message that the number must be between 0 and 17. Prompt for another number.

 

If the value is odd and between 0 and 17, display the diamond pattern on the console. With an input of 5, the first row has 1 asterisk centered at position 3 (midpoint of 5), row 2 has asterisks at position 2, 3 and 4 and row 3 in all five positions. Then the design is reversed. An input of 9 prints: 1 asterisk at position 5, 3 asterisks starting at position 4, 5 asterisks starting at position 2 and then 9 asterisks starting at column 1. Then the pattern is reversed. Each row is centered around the maximum number of asterisks to appear in that diamond pattern. After printing, prompt for another number.

 

I have included the source code for MyInput.java below so that you can use it in the homework. Just cut and paste it into Notepad or JBuilder and compile it as a separate class.

import java.io.*;

public class MyInput

{public static String readString()

  { BufferedReader br

      = new BufferedReader(new InputStreamReader(System.in), 1);

    String string = " ";

    try

    { string = br.readLine(); }

    catch (IOException ex)

    {  System.out.println(ex); }

    return string;

  }

  public static int readInt()

  { return Integer.parseInt(readString()); }

 

  public static double readDouble()

  {  return Double.parseDouble(readString());  }

}