Cleveland State University
CIS260 Lecture Notes March 10th – Chapter 6 – Iterations – Files (updated Wed. Mar 10)
V. Matos
Example1
package cis260.matos;
import java.util.Scanner;
public class Chapter6Driver {
public static void main(String[] args) throws FileNotFoundException {
// Prob. 6.1 Drawing a diamond shape (just the outline)
// get data
System.out.println("Enter symbol and desired No. of rows");
Scanner in = new Scanner(System.in);
String theSymbol = in.next();
int n = in.nextInt();
System.out.println( "ECHO " + theSymbol + " " + n);
//draw top portion of the Diamond
for (int row = 0; row <= (n-1)/2; row++)
{
//take care of leading spaces
for (int iSpace=0; iSpace < (n-(2*row +1))/2; iSpace++)
System.out.print(" ");
//print star symbol
for(int iSymbol=0; iSymbol < 2*row+1; iSymbol++)
{
if((iSymbol == 0) || (iSymbol == 2*row))
System.out.print(theSymbol);
else
System.out.print(" ");
}
System.out.println("");
}
//draw bottom portion
for(int row= n/2 + 1; row< n; row++)
{
//take care of leading spaces
for (int iSpace=0; iSpace < (2*row+1-n)/2; iSpace++)
System.out.print(" ");
//print star symbol
for(int iSymbol=0; iSymbol < 2*(n - row) - 1 ; iSymbol++)
{
if ((iSymbol == 0) || (iSymbol == 2*(n - row - 1) ) )
System.out.print(theSymbol);
else
System.out.print(" ");
}
System.out.println("");
}
}
}
Some output generated by the program
Enter symbol and desired No. of rows*
9
ECHO * 9
*
* *
* *
* *
* *
* *
* *
* *
* / Enter symbol and desired No. of rows
#
5
ECHO # 5
#
# #
# #
# #
# / Enter symbol and desired No. of rows
$
11
ECHO $ 11
$
$ $
$ $
$ $
$ $
$ $
$ $
$ $
$ $
$ $
$
Example2
package cis260.matos;
public class RandomBox {
/**
* Drawing random boxes (width and height are random values
* between 0 and MAXSIZE
*/
public static void main(String[] args) {
final int MAXSIZE = 10;
int d1 = (int) ( MAXSIZE * Math.random());
int d2 = (int) ( MAXSIZE * Math.random());
for (int row=1; row <= d1; row++)
{
for (int col=1; col <= d2; col++)
{
//working on top or bottom line
if( (row==1) || (row==d1))
{
System.out.print("*");
}
else {
//working on interior lines
if((col==1)||(col==d2)){
System.out.print("*");
}
else {
System.out.print(" ");
}
}
}
System.out.println("");
}
}
}
The program generates images such as:
* *
* *
* *
* *
******* / ********
* *
******** / ****
* *
* *
****
Example 3
package cis260.matos;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class OuputFileDemo {
/**
* creating a disk (output) file each record in the file is a
* randomly generated number between 0 and 1000
* example uses: try...catch block
*/
public static void main(String[] args) {
try {
int data;
PrintWriter myOutputFile = new PrintWriter(
new File("c:\\mydiskfile001.txt"));
for(int i=0; i<100; i++)
{
data = (int) (1001 * Math.random());
myOutputFile.println(data);
}
myOutputFile.close();
System.out.println("Done...");
} catch (FileNotFoundException e) {
System.out.println("Problems - check disk");
}
}
}