JAVA: An Introduction to Problem Solving & Programming, 8th Ed. By Walter Savitch.
ISBN 01334462033
© 2018 Pearson Education, Inc., Hoboken, NJ. All Rights Reserved

 

 

 

 

 

 

Listing 9.1

import java.util.Scanner;
public class GotMilk
{
    public static void main (String [] args)
    {
        Scanner keyboard = new Scanner (System.in);
        System.out.println ("Enter number of donuts:");
        int donutCount = keyboard.nextInt ();
        System.out.println ("Enter number of glasses of milk:");
        int milkCount = keyboard.nextInt ();
        //Dealing with an unusual event without Javas exception
        //handling features:
        if (milkCount < 1)                                          
        {                                                           
            System.out.println ("No milk!");                        
            System.out.println ("Go buy some milk.");               
        }                                                           
        else                                                        
        {
            double donutsPerGlass = donutCount / (double) milkCount;
            System.out.println (donutCount + " donuts.");           
            System.out.println (milkCount + " glasses of milk.");   
            System.out.println ("You have " + donutsPerGlass +      
                    " donuts for each glass of milk.");             
        }                                                           
        System.out.println ("End of program.");
    }
}

 

 

 

Listing 9.2

import java.util.Scanner;
public class ExceptionDemo
{
    public static void main (String [] args)
    {
        Scanner keyboard = new Scanner (System.in);
        try
        {
            System.out.println ("Enter number of donuts:");
            int donutCount = keyboard.nextInt ();
            System.out.println ("Enter number of glasses of milk:");
            int milkCount = keyboard.nextInt ();
            if (milkCount < 1)
                throw new Exception ("Exception: No milk!");
            double donutsPerGlass = donutCount / (double) milkCount;
            System.out.println (donutCount + " donuts.");
            System.out.println (milkCount + " glasses of milk.");
            System.out.println ("You have " + donutsPerGlass +
                    " donuts for each glass of milk.");
        }
        catch (Exception e)
        {
            System.out.println (e.getMessage ());
            System.out.println ("Go buy some milk.");
        }
        System.out.println ("End of program.");
    }
}

 

 

Listing 9.3

import java.util.Scanner;
public class ExceptionDemo
{
    public static void main (String [] args)
    {
        Scanner keyboard = new Scanner (System.in);
        try
        {
            System.out.println ("Enter number of donuts:");
            int donutCount = keyboard.nextInt ();
            System.out.println ("Enter number of glasses of milk:");
            int milkCount = keyboard.nextInt ();
		// assume user enters positive number of glasses of milk

            if (milkCount < 1)
                throw new Exception ("Exception: No milk!");
		// milkCount is positive so exception NOT thrown here

		// flow of control continues to here
            double donutsPerGlass = donutCount / (double) milkCount;
            System.out.println (donutCount + " donuts.");
            System.out.println (milkCount + " glasses of milk.");
            System.out.println ("You have " + donutsPerGlass
                    + " donuts for each glass of milk.");
        }// flow of control leaves here

	  // catch is NOT excecuted
        catch (Exception e)
        {
            System.out.println (e.getMessage ());
            System.out.println ("Go buy some milk.");
        }

	  // flow of control comes to here
        System.out.println ("End of program.");
    }
}

 

 

 

Listing 9.4

import java.util.Scanner;
public class ExceptionDemo
{
    public static void main (String [] args)
    {
        Scanner keyboard = new Scanner (System.in);
        try
        {
            System.out.println ("Enter number of donuts:");
            int donutCount = keyboard.nextInt ();
            System.out.println ("Enter number of glasses of milk:");
            int milkCount = keyboard.nextInt ();
		// assume user enters 0 for number of glasses of milk

            if (milkCount < 1)
                throw new Exception ("Exception: No milk!");
		// milkCount is negative so exception IS thrown here
             // flow of control jumps to catch block
		
		// flow of control skips past these lines
            double donutsPerGlass = donutCount / (double) milkCount;
            System.out.println (donutCount + " donuts.");
            System.out.println (milkCount + " glasses of milk.");
            System.out.println ("You have " + donutsPerGlass
                    + " donuts for each glass of milk.");
        }

	  // catch is IS excecuted
        catch (Exception e)
        {
            System.out.println (e.getMessage ());
            System.out.println ("Go buy some milk.");
        }

	  // flow of control comes to here after catch block
        System.out.println ("End of program.");
    }
}

 

 

 

Listing 9.5

public class DivideByZeroException extends Exception
{
    public DivideByZeroException ()
    {
        super ("Dividing by Zero!");
    }


    public DivideByZeroException (String message)
    {
        super (message);
    }
}

 

 

 

Listing 9.6

import java.util.Scanner;
public class DivideByZeroDemo
{
    private int numerator;
    private int denominator;
    private double quotient;
    public static void main (String [] args)
    {
        DivideByZeroDemo oneTime = new DivideByZeroDemo ();
        oneTime.doIt ();
    }


    public void doIt ()
    {
        try
        {
            System.out.println ("Enter numerator:");
            Scanner keyboard = new Scanner (System.in);
            numerator = keyboard.nextInt ();
            System.out.println ("Enter denominator:");
            denominator = keyboard.nextInt ();
            if (denominator == 0)
                throw new DivideByZeroException ();
            quotient = numerator / (double) denominator;
            System.out.println (numerator + "/" + denominator +
                    " = " + quotient);
        }
        catch (DivideByZeroException e)
        {
            System.out.println (e.getMessage ());
            giveSecondChance ();
        }
        System.out.println ("End of program.");
    }


    public void giveSecondChance ()
    {
        System.out.println ("Try again:");
        System.out.println ("Enter numerator:");
        Scanner keyboard = new Scanner (System.in);
        numerator = keyboard.nextInt ();
        System.out.println ("Enter denominator:");
        System.out.println ("Be sure the denominator is not zero.");
        denominator = keyboard.nextInt ();
        if (denominator == 0)                                       
        {                                                           
            System.out.println ("I cannot do division by zero.");   
            System.out.println ("Since I cannot do what you want,");
            System.out.println ("the program will now end.");       
            System.exit (0);                                        
        }                                                           
        quotient = ((double) numerator) / denominator;
        System.out.println (numerator + "/" + denominator +
                " = " + quotient);
    }
}

 

 

 

Listing 9.7

import java.util.Scanner;
public class DoDivision
{
    private int numerator;
    private int denominator;
    private double quotient;
    public static void main (String [] args)
    {
        DoDivision doIt = new DoDivision ();
        try
        {
            doIt.doNormalCase ();
        }
        catch (DivideByZeroException e)
        {
            System.out.println (e.getMessage ());
            doIt.giveSecondChance ();
        }
        System.out.println ("End of program.");
    }


    public void doNormalCase () throws DivideByZeroException
    {
        System.out.println ("Enter numerator:");
        Scanner keyboard = new Scanner (System.in);
        numerator = keyboard.nextInt ();
        System.out.println ("Enter denominator:");
        denominator = keyboard.nextInt ();
        if (denominator == 0)
            throw new DivideByZeroException ();
        quotient = numerator / (double) denominator;
        System.out.println (numerator + "/" + denominator +
                " = " + quotient);
    }

}

 

 

 

Listing 9.8

import java.util.Scanner;
public class TwoCatchesDemo
{
    public static void main (String [] args)
    {
        try
        {
            System.out.println ("Enter number of widgets produced:");
            Scanner keyboard = new Scanner (System.in);
            int widgets = keyboard.nextInt ();
            if (widgets < 0)
                throw new NegativeNumberException ("widgets");
            System.out.println ("How many were defective?");
            int defective = keyboard.nextInt ();
            if (defective < 0)
                throw new NegativeNumberException ("defective widgets");
            double ratio = exceptionalDivision (widgets, defective);
            System.out.println ("One in every " + ratio +
                    " widgets is defective.");
        }
        catch (DivideByZeroException e)
        {
            System.out.println ("Congratulations! A perfect record!");
        }
        catch (NegativeNumberException e)
        {
            System.out.println ("Cannot have a negative number of " +
                    e.getMessage ());
        }
        System.out.println ("End of program.");
    }


    public static double exceptionalDivision (double numerator,
            double denominator) throws DivideByZeroException
    {
        if (denominator == 0)
            throw new DivideByZeroException ();
        return numerator / denominator;
    }
}

 

 

 

Listing 9.9

public class NegativeNumberException extends Exception
{
    public NegativeNumberException ()
    {
        super ("Negative Number Exception!");
    }


    public NegativeNumberException (String message)
    {
        super (message);
    }
}

 

 

 

Listing 9.10

public class UnknownOpException extends Exception
{
    public UnknownOpException ()
    {
        super ("UnknownOpException");
    }


    public UnknownOpException (char op)
    {
        super (op + " is an unknown operator.");
    }


    public UnknownOpException (String message)
    {
        super (message);
    }
}

 

 

 

Listing 9.11

import java.util.Scanner;
/**
PRELIMINARY VERSION without exception handling.
Simple line-oriented calculator program. The class
can also be used to create other calculator programs.
*/
public class PrelimCalculator
{
    private double result;
    private double precision = 0.0001;
    //Numbers this close to zero are treated as if equal to zero.
    public static void main (String [] args)
        throws DivideByZeroException,
               UnknownOpException
    {
        PrelimCalculator clerk = new PrelimCalculator ();
        System.out.println ("Calculator is on.");
        System.out.print ("Format of each line: ");
        System.out.println ("operator space number");
        System.out.println ("For example: + 3");
        System.out.println ("To end, enter the letter e.");
        clerk.doCalculation ();
        System.out.println ("The final result is " +
                clerk.resultValue ());
        System.out.println ("Calculator program ending.");
    }


    public PrelimCalculator ()
    {
        result = 0;
    }


    public void reset ()
    {
        result = 0;
    }


    public void setResult (double newResult)
    {
        result = newResult;
    }


    public double getResult ()
    {
        return result;
    }


    /**
    Returns n1 op n2, provided op is one of '+', '', '*',or '/'.
    Any other value of op throws UnknownOpException.
    */
    public double evaluate (char op, double n1, double n2)
        throws DivideByZeroException, UnknownOpException
    {
        double answer;
        switch (op)
        {
            case '+':
                answer = n1 + n2;
                break;
            case '-':
                answer = n1 - n2;
                break;
            case '*':
                answer = n1 * n2;
                break;
            case '/':
                if ((-precision < n2) && (n2 < precision))
                    throw new DivideByZeroException ();
                answer = n1 / n2;
                break;
            default:
                throw new UnknownOpException (op);
        }
        return answer;
    }


    public void setResult (double newResult)
    {
        result = newResult;
    }


    public double getResult ()
    {
        return result;
    }


    /**
    Returns n1 op n2, provided op is one of '+', '', '*',or '/'.
    Any other value of op throws UnknownOpException.
    */
    public double evaluate (char op, double n1, double n2)
        throws DivideByZeroException, UnknownOpException
    {
        double answer;
        switch (op)
        {
            case '+':
                answer = n1 + n2;
                break;
            case '-':
                answer = n1 - n2;
                break;
            case '*':
                answer = n1 * n2;
                break;
            case '/':
                if ((-precision < n2) && (n2 < precision))
                    throw new DivideByZeroException ();
                answer = n1 / n2;
                break;
            default:
                throw new UnknownOpException (op);
        }
        return answer;
    }


    public void doCalculation () throws DivideByZeroException,
                                        UnknownOpException
    {
        Scanner keyboard = new Scanner (System.in);
        boolean done = false;
        result = 0;
        System.out.println ("result = " + result);
        while (!done)
        {
            char nextOp = (keyboard.next ()).charAt (0);
            if ((nextOp == 'e') || (nextOp == 'E'))
                done = true;
            else
            {
                double nextNumber = keyboard.nextDouble ();
                result = evaluate (nextOp, result, nextNumber);
                System.out.println ("result " + nextOp + " " +
                        nextNumber + " = " + result);
                System.out.println ("updated result = " + result);
            }
        }
    }
}

 

 

 

Listing 9.12

import java.util.Scanner;
/**
Simple line-oriented calculator program. The class
can also be used to create other calculator programs.
*/
public class Calculator
{
    private double result;
    private double precision = 0.0001;
    //Numbers this close to zero are treated as if equal to zero.
    public static void main (String [] args)
    {
        Calculator clerk = new Calculator ();
        try
        {
            System.out.println ("Calculator is on.");
            System.out.print ("Format of each line: ");
            System.out.println ("operator space number");
            System.out.println ("For example: + 3");
            System.out.println ("To end, enter the letter e.");
            clerk.doCalculation ();
        }
        catch (UnknownOpException e)
        {
            clerk.handleUnknownOpException (e);
        }
        catch (DivideByZeroException e)
        {
            clerk.handleDivideByZeroException (e);
        }
        System.out.println ("The final result is " +
                clerk.resultValue ());
        System.out.println ("Calculator program ending.");
    }


    public Calculator ()
    {
        result = 0;
    }


    public void
        handleDivideByZeroException (DivideByZeroException e)
    {
        System.out.println ("Dividing by zero.");
        System.out.println ("Program aborted");
        System.exit (0);
    }


    public void handleUnknownOpException (UnknownOpException e)
    {
        System.out.println (e.getMessage ());
        System.out.println ("Try again from the beginning:");
        try
        {
            System.out.print ("Format of each line: ");
            System.out.println ("operator number");
            System.out.println ("For example: + 3");
            System.out.println ("To end, enter the letter e.");
            doCalculation ();
        }
        catch (UnknownOpException e2)
        {
            System.out.println (e2.getMessage ());
            System.out.println ("Try again at some other time.");
            System.out.println ("Program ending.");
            System.exit (0);
        }
        catch (DivideByZeroException e3)
        {
            handleDivideByZeroException (e3);
        }
    }

    //The methods reset, setResult, getResult, evaluate, and doCalculation
    //are the same as in Listing 9.11.
}

 

 

 

Listing 9.13

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.layout.VBox;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.Spinner;
import javafx.scene.control.SpinnerValueFactory;
import javafx.scene.control.ChoiceBox;
import javafx.collections.FXCollections;
import javafx.scene.control.Label;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;

/**
Simple demonstration of some additional JavaFX
UI controls.
*/
public class AdditionalControlsDemo extends Application
{
   public static void main(String[] args)
   {
      launch(args);
   }

   @Override
   public void start(Stage primaryStage) throws Exception
   {
	VBox root = new VBox();

	// Demonstrate radio buttons
	root.getChildren().add(new Label("Select pizza crust"));
	ToggleGroup toggleCrust = new ToggleGroup();
	RadioButton rbHand = new RadioButton("Hand tossed");
	rbHand.setToggleGroup(toggleCrust);
	rbHand.setSelected(true);
	RadioButton rbDeepDish = new RadioButton("Deep dish");
	rbDeepDish.setToggleGroup(toggleCrust);
	root.getChildren().add(rbHand);
	root.getChildren().add(rbDeepDish);

	// Demonstrate checkboxes
	root.getChildren().add(new Label("Select pizza toppings"));
	CheckBox cbCheese = new CheckBox("Extra cheese");
	CheckBox cbPepperoni = new CheckBox("Pepperoni");
	CheckBox cbMushrooms = new CheckBox("Mushrooms");
	root.getChildren().add(cbCheese);
	root.getChildren().add(cbPepperoni);
	root.getChildren().add(cbMushrooms);

	// Demonstrate Spinner with integer values from 1-10
	root.getChildren().add(new Label("Select quantity"));
	Spinner<Integer> spinnerQuantity = new Spinner();
	final int defaultValue = 1;
	// Value factory.
	SpinnerValueFactory<Integer> quantityFactory =
         new SpinnerValueFactory.IntegerSpinnerValueFactory
                 (1, 10, defaultValue);
	spinnerQuantity.setValueFactory(quantityFactory);
	root.getChildren().add(spinnerQuantity);

	// Demonstrate ChoiceBox with delivery options
	root.getChildren().add(new Label("Select delivery mode"));
	ChoiceBox<String> cbModes = new ChoiceBox<String>(
	   FXCollections.observableArrayList("Delivery",
                                   "Dine-In", "Carryout"));
      root.getChildren().add(cbModes);

      // Button to display selections
	Button btnSelections = new Button("Get Selections");
	// Set the event handler when the button is clicked
	btnSelections.setOnAction(new EventHandler<ActionEvent>()
	{
	 	@Override
	   	public void handle(ActionEvent event)
	   	{
	   		System.out.println("Hand tossed: " + rbHand.isSelected());
	   		System.out.println("Deep dish: " +
                       rbDeepDish.isSelected());
	   		System.out.println("Cheese: " + cbCheese.isSelected());
			System.out.println("Pepperoni: " +
                       cbPepperoni.isSelected());
			System.out.println("Mushrooms: " +
                       cbMushrooms.isSelected());
			System.out.println("Quantity: " +
                       spinnerQuantity.getValue());
			System.out.println("Mode: " + cbModes.getValue());
	   	}
	   }
	);
	root.getChildren().add(btnSelections);

	Scene scene = new Scene(root, 350, 300);
	primaryStage.setTitle("Additional Controls Demo");
	primaryStage.setScene(scene);
	primaryStage.show();
   }
}

 

 

 

Listing 9.14

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.layout.VBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;

/**
Demonstration of some shapes and an image
within a VBox layout.
*/
public class ImageShapeDemo extends Application
{
   public static void main(String[] args)
   {
      launch(args);
   }

   @Override
   public void start(Stage primaryStage) throws Exception
   {
	VBox root = new VBox();
	ImageView imv = new ImageView();
	// Java looks for "java.jpg" in the default folder
	Image img = new Image("java.jpg");
	imv.setImage(img);

	Circle c = new Circle();
	c.setRadius(25);
	c.setFill(Color.PINK);

	Rectangle r = new Rectangle();
	r.setWidth(100);
	r.setHeight(50);
	r.setFill(Color.BLUE);

	root.getChildren().add(imv);
	root.getChildren().add(c);
	root.getChildren().add(r);


	Scene scene = new Scene(root, 300, 200);
	primaryStage.setTitle("Image and Shape Demo");
	primaryStage.setScene(scene);
	primaryStage.show();
   }
}

 

 

 

Listing 9.15

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.Group;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.input.MouseEvent;
import javafx.event.EventHandler;
import java.util.Random;

/**
This program draws a circle of random color
at the location of the mouse whenever the mouse
moves.
*/
public class MousePaint extends Application
{
   private Random rnd = new Random();

   public static void main(String[] args)
   {
      Application.launch(args);
   }

   @Override
   public void start(Stage primaryStage) throws Exception
   {
	Group root = new Group();
	Canvas canvas = new Canvas(650, 600);
	GraphicsContext gc = canvas.getGraphicsContext2D();

	// When the mouse is pressed erase the
	// screen by drawing a white rectangle on the
	// entire canvas
	canvas.setOnMousePressed(new EventHandler<MouseEvent>()
	{
        @Override
        public void handle(MouseEvent event)
        {
      	gc.setFill(Color.WHITE);
          	gc.fillRect(0,0,canvas.getWidth(),canvas.getHeight());
        }
	});

	// When the mouse is moved get a random color
	// and draw a circle at the mouse's coordinates
	canvas.setOnMouseMoved(new EventHandler<MouseEvent>()
	{
         @Override
		public void handle(MouseEvent event)
         {
	     // Get a random color
           gc.setFill(Color.rgb(rnd.nextInt(255),
                rnd.nextInt(255),
                rnd.nextInt(255)));
           gc.fillOval(event.getX(),event.getY(),100,100);
         }
	});

	root.getChildren().add(canvas);
	primaryStage.setScene(new Scene(root));
	primaryStage.setTitle("Mouse Paint");
	primaryStage.show();
   }
}

 

 

 

Listing 9.16

import javafx.application.Application;
import javafx.scene.canvas.Canvas;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.input.MouseEvent;
import javafx.event.EventHandler;
import javafx.scene.shape.Circle;

/**
This program sets the X/Y coordinates of a Circle to the
location of the mouse.
*/
public class MouseCircle extends Application
{
   public static void main(String[] args)
   {
      Application.launch(args);
   }

   @Override
   public void start(Stage primaryStage) throws Exception
   {
	Pane root = new Pane();
	root.setPrefSize(400,400);

	Circle circle = new Circle();
	circle.setRadius(30);
	circle.setFill(Color.RED);

	root.setOnMouseMoved(new EventHandler<MouseEvent>()
	{
       	@Override
       	public void handle(MouseEvent event)
       	{
        		circle.setCenterX(event.getX());
        		circle.setCenterY(event.getY());
      	}
	});

	root.getChildren().add(circle);
	primaryStage.setScene(new Scene(root));
	primaryStage.setTitle("Mouse Circle");
	primaryStage.show();
   }
} 

 

 

 

Listing 9.17

import javafx.scene.shape.Circle;
import javafx.scene.paint.Color;
import java.util.Random;

public class Ball extends Circle
{
  private static final int RADIUS = 30;
  private int x,y;
  private int xVel, yVel;

  public Ball()
  {
	Random rnd = new Random();

      setRadius(RADIUS);
      setFill(Color.RED);
      x = 50;
      y = 50;
      xVel = rnd.nextInt(20) + 5;
      yVel = rnd.nextInt(20) + 5;
  }

  public void updateLocation()
  {
	  x += xVel;
	  y += yVel;
	  setCenterX(x);
	  setCenterY(y);
  }

  public int getX()
  {
	  return x;
  }

  public int getY()
  {
	  return y;
  }

  public void reverseX()
  {
	  xVel *= -1;
  }

  public void reverseY()
  {
	  yVel *= -1;
  }
}

 

 

 

Listing 9.18

import javafx.application.Application;
import javafx.scene.canvas.Canvas;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.layout.Pane;
import javafx.event.EventHandler;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.util.Duration;
import javafx.event.ActionEvent;

/**
This program animates a red ball within
The window.
*/
public class BounceBall extends Application
{
   public static void main(String[] args)
   {
      Application.launch(args);
   }

   @Override
   public void start(Stage primaryStage) throws Exception
   {
	Pane root = new Pane();
	root.setPrefSize(400,400);

	Ball ball = new Ball();

	// Timeline to call the event handler every 10ms
	// to update a bouncing ball
	Timeline timeline = new Timeline(
        new KeyFrame(Duration.millis(10),
               new EventHandler()
			   {
			   	@Override
			   	public void handle(ActionEvent event)
			   	{
			   		ball.updateLocation();
			   		if ((ball.getX() < 0) ||
			   		    (ball.getX() > root.getWidth()))
			   			ball.reverseX();
			   		if ((ball.getY() < 0) ||
			   		    (ball.getY() > root.getHeight()))
			   			ball.reverseY();
			   	}
			   }
        )
	);
	timeline.setCycleCount(Timeline.INDEFINITE);
	timeline.setAutoReverse(true);
	timeline.play();

	root.getChildren().add(ball);
	primaryStage.setScene(new Scene(root));
	primaryStage.setTitle("Bouncing Ball");
	primaryStage.show();
   }
}

 

 

 

Listing 10.1

import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TextFileOutputDemo
{
    public static void main (String [] args)
    {
        String fileName = "out.txt"; //The name could be read from
        //the keyboard.
        PrintWriter outputStream = null;
        try
        {
            outputStream = new PrintWriter (fileName);
        }
        catch (FileNotFoundException e)
        {
            System.out.println ("Error opening the file " +
                    fileName);
            System.exit (0);
        }
        System.out.println ("Enter three lines of text:");
        Scanner keyboard = new Scanner (System.in);
        for (int count = 1 ; count <= 3 ; count++)
        {
            String line = keyboard.nextLine ();
            outputStream.println (count + " " + line);
        }
        outputStream.close ();
        System.out.println ("Those lines were written to " +
                fileName);
    }
}

 

 

 

Listing 10.2

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class TextFileInputDemo
{
    public static void main (String [] args)
    {
        String fileName = "out.txt";
        Scanner inputStream = null;
        System.out.println ("The file " + fileName +
                "\ncontains the following lines:\n");
        try
        {
            inputStream = new Scanner (new File (fileName));
        }
        catch (FileNotFoundException e)
        {
            System.out.println ("Error opening the file " +
                    fileName);
            System.exit (0);
        }
        while (inputStream.hasNextLine ())
        {
            String line = inputStream.nextLine ();
            System.out.println (line);
        }
        inputStream.close ();
    }
}

 

 

Listing 10.3

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class TextFileInputDemo2
{
    public static void main (String [] args)
    {
        System.out.print ("Enter file name: ");    
        Scanner keyboard = new Scanner (System.in);
        String fileName = keyboard.next ();        
        Scanner inputStream = null;
        System.out.println ("The file " + fileName + "\n" +
                "contains the following lines:\n");
        try
        {
            inputStream = new Scanner (new File (fileName));
        }
        catch (FileNotFoundException e)
        {
            System.out.println ("Error opening the file " +
                    fileName ");
                    System.exit (0);
        }
        while (inputStream.hasNextLine ())
        {
            String line = inputStream.nextLine ();
            System.out.println (line);
        }
        inputStream.close ();
    }
}

 

 

 

Listing 10.4


File: Transactions.txt
SKU,Quantity,Price,Description
4039,50,0.99,SODA
9100,5,9.50,T-SHIRT
1949,30,110.00,JAVA PROGRAMMING TEXTBOOK
5199,25,1.50,COOKIE


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;

public class TransactionReader
{
    public static void main(String[] args)
    {
        String fileName = "Transactions.txt";
        try
        {
            Scanner inputStream = new Scanner(new File(fileName));
            // Read the header line
            String line = inputStream.nextLine();
			// Total sales
            double total = 0;
            // Read the rest of the file line by line
            while (inputStream.hasNextLine())
            {
				// Contains SKU,Quantity,Price,Description
				line = inputStream.nextLine();
				// Turn the string into an array of strings
				String[] ary = line.split(",");
				// Extract each item
				String SKU = ary[0];
				int quantity = Integer.parseInt(ary[1]);
				double price = Double.parseDouble(ary[2]);
				String description = ary[3];
				// Output item
				System.out.printf("Sold %d of %s (SKU: %s) at $%1.2f each.\n",
					quantity, description, SKU, price);
				// Compute total
				total += quantity * price;
			}
			System.out.printf("Total sales: $%1.2f\n",total);
            inputStream.close( );
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Cannot find file " + fileName);
        }
        catch(IOException e)
        {
            System.out.println("Problem with input from file " + fileName);
        }
    }
}
        

 

 

 

Listing 10.5

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class BinaryOutputDemo
{
    public static void main (String [] args)
    {
        String fileName = "numbers.dat";
        try
        {
            ObjectOutputStream outputStream =
                new ObjectOutputStream (new FileOutputStream (fileName));
            Scanner keyboard = new Scanner (System.in);
            System.out.println ("Enter nonnegative integers.");
            System.out.println ("Place a negative number at the end.");
            int anInteger;
            do
            {
                anInteger = keyboard.nextInt ();
                outputStream.writeInt (anInteger);
            }
            while (anInteger >= 0);
            System.out.println ("Numbers and sentinel value");
            System.out.println ("written to the file " + fileName);
            outputStream.close ();
        }
        catch (FileNotFoundException e)
        {
            System.out.println ("Problem opening the file " + fileName);
        }
        catch (IOException e)
        {
            System.out.println ("Problem with output to file " + fileName);
        }
    }
}

 

 

 

Listing 10.6

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class BinaryInputDemo
{
    public static void main (String [] args)
    {
        String fileName = "numbers.dat";
        try
        {
            ObjectInputStream inputStream =
                new ObjectInputStream (new FileInputStream (fileName));
            System.out.println ("Reading the nonnegative integers");
            System.out.println ("in the file " + fileName);
            int anInteger = inputStream.readInt ();
            while (anInteger >= 0)
            {
                System.out.println (anInteger);
                anInteger = inputStream.readInt ();
            }
            System.out.println ("End of reading from file.");
            inputStream.close ();
        }
        catch (FileNotFoundException e)
        {
            System.out.println ("Problem opening the file " + fileName);
        }
        catch (EOFException e)
        {
            System.out.println ("Problem reading the file " + fileName);
            System.out.println ("Reached end of the file.");
        }
        catch (IOException e)
        {
            System.out.println ("Problem eading the file " + fileName);
        }
    }
}

 

 

 

Listing 10.7

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
public class EOFExceptionDemo
{
    public static void main (String [] args)
    {
        String fileName = "numbers.dat";
        try
        {
            ObjectInputStream inputStream =
                new ObjectInputStream (new FileInputStream (fileName));
            System.out.println ("Reading ALL the integers");
            System.out.println ("in the file " + fileName);
            try
            {
                while (true)
                {
                    int anInteger = inputStream.readInt ();
                    System.out.println (anInteger);
                }
            }
            catch (EOFException e)
            {
                System.out.println ("End of reading from file.");
            }
            inputStream.close ();
        }
        catch (FileNotFoundException e)
        {
            System.out.println ("Cannot find file " + fileName);
        }
        catch (IOException e)
        {
            System.out.println ("Problem with input from file " + fileName);
        }
    }
}

 

 

 

Listing 10.8

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Doubler
{
    private ObjectInputStream inputStream = null;
    private ObjectOutputStream outputStream = null;
    /**
    Doubles the integers in one file and puts them in another file.
    */
    public static void main (String [] args)
    {
        Doubler twoTimer = new Doubler ();
        twoTimer.connectToInputFile ();
        twoTimer.connectToOutputFile ();
        twoTimer.timesTwo ();
        twoTimer.closeFiles ();
        System.out.println ("Numbers from input file");
        System.out.println ("doubled and copied to output file.");
    }


    public void connectToInputFile ()
    {
        String inputFileName =
            getFileName ("Enter name of input file:");
        try
        {
            inputStream = new ObjectInputStream (
                    new FileInputStream (inputFileName));
        }
        catch (FileNotFoundException e)
        {
            System.out.println ("File " + inputFileName +
                    " not found.");
            System.exit (0);
        }
        catch (IOException e)
        {
            System.out.println ("Error opening input file " +
                    inputFileName);
            System.exit (0);
        }
    }


    private String getFileName (String prompt)
    {
        String fileName = null;
        System.out.println (prompt);
        Scanner keyboard = new Scanner (System.in);
        fileName = keyboard.next ();
        return fileName;
    }


    public void connectToOutputFile ()
    {
        String outputFileName =
            getFileName ("Enter name of output file:");
        try
        {
            outputStream = new ObjectOutputStream (
                    new FileOutputStream (outputFileName));
        }
        catch (IOException e)
        {
            System.out.println ("Error opening output file " +
                    outputFileName);
            System.out.println (e.getMessage ());
            System.exit (0);
        }
    }


    public void timesTwo ()
    {
        try
        {
            while (true)
            {
                int next = inputStream.readInt ();
                outputStream.writeInt (2 * next);
            }
        }
        catch (EOFException e)                    
        {                                         
            //Do nothing. This just ends the loop.
        }                                         
        catch (IOException e)
        {
            System.out.println (
                    "Error: reading or writing files.");
            System.out.println (e.getMessage ());
            System.exit (0);
        }
    }


    public void closeFiles ()
    {
        try
        {
            inputStream.close ();
            outputStream.close ();
        }
        catch (IOException e)
        {
            System.out.println ("Error closing files " +
                    e.getMessage ());
            System.exit (0);
        }
    }
}

 

 

 

Listing 10.9

import java.io.Serializable;
import java.util.Scanner;
/**
Serialized class for data on endangered species.
*/
public class Species implements Serializable
{
    private String name;
    private int population;
    private double growthRate;
    public Species ()
    {
        name = null;
        population = 0;
        growthRate = 0;
    }


    public Species (String initialName, int initialPopulation,
            double initialGrowthRate)
    {
        name = initialName;
        if (initialPopulation >= 0)
            population = initialPopulation;
        else
        {
            System.out.println ("ERROR: Negative population.");
            System.exit (0);
        }
        growthRate = initialGrowthRate;
    }


    public String toString ()
    {
        return ("Name = " + name + "\n" +
                "Population = " + population + "\n" +
                "Growth rate = " + growthRate + "%");
    }


    //Other methods are the same as those in Listing 5.17 of Chapter 5,
    //but they are not needed for the discussion in this chapter.
}

 

 

 

Listing 10.10

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ClassObjectIODemo
{
    public static void main (String [] args)
    {
        ObjectOutputStream outputStream = null;
        String fileName = "species.records";
        try
        {
            outputStream = new ObjectOutputStream (
                    new FileOutputStream (fileName));
        }
        catch (IOException e)
        {
            System.out.println ("Error opening output file " +
                    fileName + ".");
            System.exit (0);
        }
        Species califCondor =
            new Species ("Calif. Condor", 27, 0.02);
        Species blackRhino =
            new Species ("Black Rhino", 100, 1.0);
        try
        {
            outputStream.writeObject (califCondor);
            outputStream.writeObject (blackRhino); 
            outputStream.close ();
        }
        catch (IOException e)
        {
            System.out.println ("Error writing to file " +
                    fileName + ".");
            System.exit (0);
        }
        System.out.println ("Records sent to file " +
                fileName + ".");
        System.out.println (
                "Now let's reopen the file and echo the records.");
        ObjectInputStream inputStream = null;
        try
        {
            inputStream = new ObjectInputStream (
                    new FileInputStream ("species.records"));
        }
        catch (IOException e)
        {
            System.out.println ("Error opening input file " +
                    fileName + ".");
            System.exit (0);
        }
        Species readOne = null, readTwo = null;
        try
        {
            readOne = (Species) inputStream.readObject ();
            readTwo = (Species) inputStream.readObject ();
            inputStream.close ();
        }
        catch (Exception e)
        {
            System.out.println ("Error reading from file " +
                    fileName + ".");
            System.exit (0);
        }
        System.out.println ("The following were read\n" +
                "from the file " + fileName + ".");
        System.out.println (readOne);
        System.out.println ();
        System.out.println (readTwo);
        System.out.println ("End of program.");
    }
}

 

 

 

Listing 10.11

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ArrayIODemo
{
    public static void main (String [] args)
    {
        Species [] oneArray = new Species [2];
        oneArray [0] = new Species ("Calif. Condor", 27, 0.02);
        oneArray [1] = new Species ("Black Rhino", 100, 1.0);
        String fileName = "array.dat";
        try
        {
            ObjectOutputStream outputStream =
                new ObjectOutputStream (
                    new FileOutputStream (fileName));
            outputStream.writeObject (oneArray);
            outputStream.close ();
        }
        catch (IOException e)
        {
            System.out.println ("Error writing to file " +
                    fileName + ".");
            System.exit (0);
        }
        System.out.println ("Array written to file " +
                fileName + " and file is closed.");
        System.out.println ("Open the file for input and " +
                "echo the array.");
        Species [] anotherArray = null;
        try
        {
            ObjectInputStream inputStream =
                new ObjectInputStream (
                    new FileInputStream (fileName));
            anotherArray = (Species []) inputStream.readObject ();
            inputStream.close ();
        }
        catch (Exception e)
        {
            System.out.println ("Error reading file " +
                    fileName + . );
            System.exit (0);
        }
        System.out.println ("The following were read from " +
                "the file " + fileName + ":");
        for (int i = 0 ; i < anotherArray.length ; i++)
        {
            System.out.println (anotherArray [i]);
            System.out.println ();
        }
        System.out.println ("End of program.");
    }
}

 

 

 

Listing 10.12

import java.util.Scanner;
import java.io.InputStreamReader;
import java.io.DataOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.ServerSocket;

public class SocketServer
{
 public static void main(String[] args)
 {
  String s;
  Scanner inputStream = null;
  PrintWriter outputStream = null;
  ServerSocket serverSocket = null;
  try
  {
	 // Wait for connection on port 6789
	 System.out.println("Waiting for a connection.");
	 serverSocket = new ServerSocket(6789);
	 Socket socket = serverSocket.accept();
	 // Connection made, set up streams
	 inputStream = new Scanner(new InputStreamReader(socket.getInputStream()));
     outputStream = new PrintWriter(new DataOutputStream(socket.getOutputStream()));

     // Read a line from the client
	 s = inputStream.nextLine();

	 // Output text to the client
     outputStream.println("Well, ");
	 outputStream.println(s + " is a fine programming language!");
     outputStream.flush();
	 System.out.println("Closing connection from " + s);
	 inputStream.close();
	 outputStream.close();
  }
  catch (Exception e)
  {
     // If any exception occurs, display it
     System.out.println("Error " + e);
  }
 }
}

 

 

 

Listing 10.13

import java.util.Scanner;
import java.io.InputStreamReader;
import java.io.DataOutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketClient
{
 public static void main(String[] args)
 {
  String s;
  Scanner inputStream = null;
  PrintWriter outputStream = null;
  try
  {
   // Connect to server on same machine, port 6789
   Socket clientSocket = new Socket("localhost",6789);
   // Set up streams to send/receive data
   inputStream = new Scanner(new InputStreamReader(clientSocket.getInputStream()));
   outputStream = new PrintWriter(new DataOutputStream(clientSocket.getOutputStream()));

   // Send "Java" to the server
   outputStream.println("Java");
   outputStream.flush(); // Sends data to the stream

   // Read everything from the server until no more lines
   // and output it to the screen
   while (inputStream.hasNextLine())
   {
     s = inputStream.nextLine();
     System.out.println(s);
   }
   inputStream.close();
   outputStream.close();
  }
  catch (Exception e)
  {
   // If any exception occurs, display it
   System.out.println("Error " + e);
  }
 }
}

 

 

 

Listing 10.14

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.layout.FlowPane;
import javafx.scene.control.TextField;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileOrganizer extends Application
{
   private TextField fileNameField;
   private TextField firstLineField;

   public static void main(String[] args)
   {
      launch(args);
   }

   @Override
   public void start(Stage primaryStage) throws Exception
   {
        final int WIDTH = 400;
        final int HEIGHT = 300;
        final int NUMBER_OF_PIXELS = 300;

	  FlowPane root = new FlowPane();

	  Button showButton = new Button("Show first line");
	  root.getChildren().add(showButton);
	  showButton.setOnAction(new EventHandler<ActionEvent>()
	   {
	   	@Override
	   	public void handle(ActionEvent event)
	   	{
	   		showFirstLine();
	   	}
	   }
	  );

	  Button removeButton = new Button("Remove file");
	  root.getChildren().add(removeButton);
	  removeButton.setOnAction(new EventHandler<ActionEvent>()
	   {
	   	@Override
	   	public void handle(ActionEvent event)
	   	{
	   		removeFile();
	   	}
	   }
	  );

	  Button resetButton = new Button("Reset");
	  root.getChildren().add(resetButton);
	  resetButton.setOnAction(new EventHandler<ActionEvent>()
	   {
	   	@Override
	   	public void handle(ActionEvent event)
	   	{
	   		resetFields();
	   	}
	   }
	  );

	  fileNameField = new TextField("Enter file name here.");
	  fileNameField.setPrefWidth(NUMBER_OF_PIXELS);
	  root.getChildren().add(fileNameField);

	  firstLineField = new TextField();
	  firstLineField.setPrefWidth(NUMBER_OF_PIXELS);
	  root.getChildren().add(firstLineField);

   	  Scene scene = new Scene(root, WIDTH, HEIGHT);
        primaryStage.setTitle("File Organizer");
        primaryStage.setScene(scene);
        primaryStage.show();
   }

    private void showFirstLine( )
    {
        Scanner fileInput = null;
        String fileName = fileNameField.getText( );
        File fileObject = new File(fileName);

        if (!fileObject.exists( ))
            firstLineField.setText("No such file");
        else if (!fileObject.canRead( ))
            firstLineField.setText("That file is not readable.");
        else
        {
            try
            {
                fileInput = new Scanner(fileObject);
            }
            catch(FileNotFoundException e)
            {
                firstLineField.setText("Error opening the file " +
                                        fileName);
            }
            String firstLine = fileInput.nextLine( );
            firstLineField.setText(firstLine);
            fileInput.close( );
        }
    }

    private void resetFields()
    {
        fileNameField.setText("Enter file name here.");
        firstLineField.setText("");
    }

    private void removeFile( )
    {
        Scanner fileInput = null;
        String firstLine;
        String fileName = fileNameField.getText( );
        File fileObject = new File(fileName);

        if (!fileObject.exists( ))
            firstLineField.setText("No such file");
        else if (!fileObject.canWrite( ))
            firstLineField.setText("Permission denied.");
        else
        {
            if (fileObject.delete( ))
                firstLineField.setText("File deleted.");
            else
                firstLineField.setText("Could not delete file.");
        }
    }
}