The sample program
While we have covered a lot of ground already, there is one last bit of information we need before we can go over the sample program. That is sending output to the console. Java programs automatically create an instance of the System class, which can be used to send output to the console by using Systems out class, which has a println statement. In other words, when you see System.out.println(text to output); you are seeing a fairly complex method call.
Here is the source code (see sidebar to download it with the compiled version). Dots represents lines.
- package com.blazinggames.jgd.chapter03;
-
- /**
- Billy Spelchan's guide to Java Game Development
- Chapter 3 sample application
- Copyright (c) 2002 Spelchan Software.
- This source code is meant for educational purposes.
- You may transfer and use this program for non-comercial purposes as long as
- no fees are charged for this program.
- The goal of this program is to demonstrate the structure of a Java application.
-
- @author Billy D. Spelchan
- @version 1.00.021118
- */
-
- public class Chapter03
{
- /**
* The MAIN method. This is where all the action takes place!
*
* @param args an array of strings containing arguments
*/
- public static void main(String args[])
{
- // variables to hold the converted integers
- int firstNumber = 0;
- int secondNumber = 0;
- int addNumber;
- int subNumber;
- int multNumber;
- double divNumber;
-
- // read the first argument and convert it into an integer
- try
- {
- firstNumber = Integer.parseInt(args[0]);
- secondNumber = Integer.parseInt(args[1]);
- }
- catch (ArrayIndexOutOfBoundsException aie)
- {
- System.out.println("Missing argument(s), so exiting");
- System.exit(1);
- }
- catch (NumberFormatException nfe)
- {
- System.out.println("Arguments must be numbers! Exiting!");
- System.exit(2);
- }
-
- // show the arguments
- System.out.println("First number is " + firstNumber);
- System.out.println("Second number is " + secondNumber);
- System.out.println();
-
- // do the first three operations
- addNumber = firstNumber + secondNumber;
- subNumber = firstNumber - secondNumber;
- multNumber = firstNumber * secondNumber;
- System.out.println(firstNumber + " + " + secondNumber + " = " + addNumber);
- System.out.println(firstNumber + " - " + secondNumber + " = " + subNumber);
- System.out.println(firstNumber + " / " + secondNumber + " = " + multNumber);
-
- // with dividing, we may have to worry about division by zero
- try
- {
- divNumber = (double)firstNumber / (double)secondNumber;
- System.out.println(firstNumber + " / " + secondNumber + " = " + divNumber);
- }
- catch (ArithmeticException ae)
- {
- System.out.println("Can not divide by zero!");
- }
- }
- }