Java/Development Class/Console

Материал из Java эксперт
Перейти к: навигация, поиск

A representation of the command line arguments passed to a Java class" main(String[]) method

  
/* 
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 *
 * CommandLine is a representation of the command line arguments passed to 
 * a Java class" main(String[]) method. It parses the arguments for flags 
 * (tokens prefixed with a dash ("-")), flag-value pairs, and an ordered 
 * list of argument values.
 *
 * @author Dan Jemiolo (danj)
 *
 */
public class CommandLine
{
    //
    // all non-flag values
    //
    private String[] _arguments = null;
    
    //
    // the flags (-foo) that were found on the command line
    //
    private Map _flags = new HashMap();
    
    //
    // the flag values that are expected to be followed with a value 
    // that allows the application to process the flag.
    //
    private Set _flagsWithValues = new HashSet();
    
    /**
     * 
     * @return All of the values specified on the command line that were 
     *         not a flag or associated with a flag.
     *
     */
    public String[] getArguments()
    {
        return _arguments;
    }
    
    /**
     * 
     * @param flagName
     * 
     * @return The value that was specified after the flag, or null if 
     *         the flag was not specified.
     *
     * @see #hasFlag(String)
     * 
     */
    public String getFlagValue(String flagName)
    {
        return (String)_flags.get(flagName);
    }
    
    public int getNumberOfArguments()
    {
        return _arguments.length;
    }
    
    public int getNumberOfFlags()
    {
        return _flags.size();
    }
    
    /**
     * 
     * @param flagName
     * 
     * @return True if the flag was specified on the command line.
     *
     */
    public boolean hasFlag(String flagName)
    {
        return _flags.containsKey(flagName);
    }
    
    /**
     * 
     * Reads through each argument in the given array, picking out the 
     * flags (and optionally,their values) from the regular arguments. 
     * Users should use the saveFlagValue(String) method before this one 
     * in order to have their command line parsed correctly.
     *
     * @param args
     *        The command line arguments given to the application.
     *
     */
    public void parse(String[] args)
    {
        List regularArgs = new ArrayList();
        
        for (int n = 0; n < args.length; ++n)
        {
            if (args[n].charAt(0) == "-")
            {
                String name = args[n];
                String value = null;
                
                if (_flagsWithValues.contains(args[n]) && 
                    n < args.length - 1)
                    value = args[++n];
                
                _flags.put(name, value);
            }
            
            else
                regularArgs.add(args[n]);
        }
        
        int size = regularArgs.size();
        _arguments = (String[])regularArgs.toArray(new String[size]);
    }
    /**
     * 
     * Tells the command line parser to associate the given flag with the 
     * value that comes after it in the list of arguments (if the flag is 
     * found). This will allow the user to retrieve the flag-value pair 
     * later and prevent the flag value from being lumped in with the 
     * regular arguments.
     *
     * @param flagName
     *
     */
    public void saveFlagValue(String flagName)
    {
        _flagsWithValues.add(flagName);
    }
}





Command line input

 
/*
 * Copyright (c) 2000 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 2nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book (recommended),
 * visit http://www.davidflanagan.ru/javaexamples2.
 */
/**
 * This program prints out all its command-line arguments.
 */
public class Echo1 {
  public static void main(String[] args) {
    int i = 0; // Initialize the loop variable
    while (i < args.length) { // Loop until the end of array
      System.out.print(args[i] + " "); // Print each argument out
      i++; // Increment the loop variable
    }
    System.out.println(); // Terminate the line
  }
}





How to deal with the console parameters

 
public class ConsoleArguments {
  public static void main(String[] args) {
    if (args.length == 0) {
      System.out.println("No arguments");
    } else {
      System.out.println("Arguments:");
      for (int i = 0; i < args.length; i++) {
        System.out.println(args[i]);
      }
    }
  }
}





How to read from standard input

 
// : c12:Echo.java
// How to read from standard input.
// {RunByHand}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.*;
public class Echo {
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String s;
    while ((s = in.readLine()) != null && s.length() != 0)
      System.out.println(s);
    // An empty line or Ctrl-Z terminates the program
  }
} ///:~





Java program to calculate the area of a circle

 
/*
Java Programming for Engineers
Julio Sanchez
Maria P. Canton

ISBN: 0849308100
Publisher: CRC Press
*/
// File name: Area.java
//Reference: Chapter 5
//
//Java program to calculate the area of a circle
//Topics:
// 1. Using numeric variables and constants
// 2. Obtaining keyboard input
// 3. Displaying program data
// 4. Performing simple numeric calculations
//
//Requires:
// 1. Keyin class in the current directory
public class Area {
  // Constant PI is defined at the class level
  static final double PI = 3.141592653589793;
  public static void main(String[] args) {
    // Local variables
    double radius, area;
    // Input radius from keyboard
    radius = Keyin.inDouble("Enter radius: ");
    // Perform calculations and display result
    area = PI * (radius * radius);
    System.out.println("The area is: " + area);
  }
}
//**********************************************************
//**********************************************************
//Program: Keyin
//Reference: Session 20
//Topics:
//   1. Using the read() method of the ImputStream class
//      in the java.io package
//   2. Developing a class for performing basic console
//      input of character and numeric types
//**********************************************************
//**********************************************************
class Keyin {
  //*******************************
  //   support methods
  //*******************************
  //Method to display the user"s prompt string
  public static void printPrompt(String prompt) {
    System.out.print(prompt + " ");
    System.out.flush();
  }
  //Method to make sure no data is available in the
  //input stream
  public static void inputFlush() {
    int dummy;
    int bAvail;
    try {
      while ((System.in.available()) != 0)
        dummy = System.in.read();
    } catch (java.io.IOException e) {
      System.out.println("Input error");
    }
  }
  //********************************
  //  data input methods for
  //string, int, char, and double
  //********************************
  public static String inString(String prompt) {
    inputFlush();
    printPrompt(prompt);
    return inString();
  }
  public static String inString() {
    int aChar;
    String s = "";
    boolean finished = false;
    while (!finished) {
      try {
        aChar = System.in.read();
        if (aChar < 0 || (char) aChar == "\n")
          finished = true;
        else if ((char) aChar != "\r")
          s = s + (char) aChar; // Enter into string
      }
      catch (java.io.IOException e) {
        System.out.println("Input error");
        finished = true;
      }
    }
    return s;
  }
  public static int inInt(String prompt) {
    while (true) {
      inputFlush();
      printPrompt(prompt);
      try {
        return Integer.valueOf(inString().trim()).intValue();
      }
      catch (NumberFormatException e) {
        System.out.println("Invalid input. Not an integer");
      }
    }
  }
  public static char inChar(String prompt) {
    int aChar = 0;
    inputFlush();
    printPrompt(prompt);
    try {
      aChar = System.in.read();
    }
    catch (java.io.IOException e) {
      System.out.println("Input error");
    }
    inputFlush();
    return (char) aChar;
  }
  public static double inDouble(String prompt) {
    while (true) {
      inputFlush();
      printPrompt(prompt);
      try {
        return Double.valueOf(inString().trim()).doubleValue();
      }
      catch (NumberFormatException e) {
        System.out
            .println("Invalid input. Not a floating point number");
      }
    }
  }
}





Java program to demonstrate menu selection

 
/*
Java Programming for Engineers
Julio Sanchez
Maria P. Canton

ISBN: 0849308100
Publisher: CRC Press
*/

// File name: MenuDemo.java
//Reference: Chapter 9
//
//Java program to demonstrate menu selection
//Topics:
// 1. Using the switch construct
//
//Requires:
// 1. Keyin class in the current directory
public class ConsoleMenuDemo {
  public static void main(String[] args) {
    // Local variable
    int swValue;
    // Display menu graphics
    System.out.println("============================");
    System.out.println("|   MENU SELECTION DEMO    |");
    System.out.println("============================");
    System.out.println("| Options:                 |");
    System.out.println("|        1. Option 1       |");
    System.out.println("|        2. Option 2       |");
    System.out.println("|        3. Exit           |");
    System.out.println("============================");
    swValue = Keyin.inInt(" Select option: ");
    // Switch construct
    switch (swValue) {
    case 1:
      System.out.println("Option 1 selected");
      break;
    case 2:
      System.out.println("Option 2 selected");
      break;
    case 3:
      System.out.println("Exit selected");
      break;
    default:
      System.out.println("Invalid selection");
      break; // This break is not really necessary
    }
  }
}
//**********************************************************
//**********************************************************
//Program: Keyin
//Reference: Session 20
//Topics:
// 1. Using the read() method of the ImputStream class
//    in the java.io package
// 2. Developing a class for performing basic console
//    input of character and numeric types
//**********************************************************
//**********************************************************
class Keyin {
  //*******************************
  //   support methods
  //*******************************
  //Method to display the user"s prompt string
  public static void printPrompt(String prompt) {
    System.out.print(prompt + " ");
    System.out.flush();
  }
  //Method to make sure no data is available in the
  //input stream
  public static void inputFlush() {
    int dummy;
    int bAvail;
    try {
      while ((System.in.available()) != 0)
        dummy = System.in.read();
    } catch (java.io.IOException e) {
      System.out.println("Input error");
    }
  }
  //********************************
  //  data input methods for
  //string, int, char, and double
  //********************************
  public static String inString(String prompt) {
    inputFlush();
    printPrompt(prompt);
    return inString();
  }
  public static String inString() {
    int aChar;
    String s = "";
    boolean finished = false;
    while (!finished) {
      try {
        aChar = System.in.read();
        if (aChar < 0 || (char) aChar == "\n")
          finished = true;
        else if ((char) aChar != "\r")
          s = s + (char) aChar; // Enter into string
      }
      catch (java.io.IOException e) {
        System.out.println("Input error");
        finished = true;
      }
    }
    return s;
  }
  public static int inInt(String prompt) {
    while (true) {
      inputFlush();
      printPrompt(prompt);
      try {
        return Integer.valueOf(inString().trim()).intValue();
      }
      catch (NumberFormatException e) {
        System.out.println("Invalid input. Not an integer");
      }
    }
  }
  public static char inChar(String prompt) {
    int aChar = 0;
    inputFlush();
    printPrompt(prompt);
    try {
      aChar = System.in.read();
    }
    catch (java.io.IOException e) {
      System.out.println("Input error");
    }
    inputFlush();
    return (char) aChar;
  }
  public static double inDouble(String prompt) {
    while (true) {
      inputFlush();
      printPrompt(prompt);
      try {
        return Double.valueOf(inString().trim()).doubleValue();
      }
      catch (NumberFormatException e) {
        System.out
            .println("Invalid input. Not a floating point number");
      }
    }
  }
}





Output to standard output and standard error; and input from standard input.

 
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class InputOutputDemoStandardInputOutput {
  public static void main(String[] a) throws Exception {
    //Write characters to standard output and standard error:
    System.out.println("std output");
    System.err.println("std error");
    //Read characters from standard input (the keyboard):
    System.out.print("Type some characters and press Enter: ");
    BufferedReader bisr = new BufferedReader(new InputStreamReader(
        System.in));
    String response = bisr.readLine();
    System.out.println("You typed: "" + response + """);
    //Read a byte from standard input (the keyboard):
    System.out.print("Type one character and press Enter: ");
    byte b = (byte) System.in.read();
    System.out.println("First byte of your input is: " + b);
  }
}





Processing the command line

  
/**
 * Redistribution and use of this software and associated documentation
 * ("Software"), with or without modification, are permitted provided
 * that the following conditions are met:
 *
 * 1. Redistributions of source code must retain copyright
 *    statements and notices.  Redistributions must also contain a
 *    copy of this document.
 *
 * 2. Redistributions in binary form must reproduce the
 *    above copyright notice, this list of conditions and the
 *    following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. The name "Exolab" must not be used to endorse or promote
 *    products derived from this Software without prior written
 *    permission of Exoffice Technologies.  For written permission,
 *    please contact info@exolab.org.
 *
 * 4. Products derived from this Software may not be called "Exolab"
 *    nor may "Exolab" appear in their names without prior written
 *    permission of Exoffice Technologies. Exolab is a registered
 *    trademark of Exoffice Technologies.
 *
 * 5. Due credit should be given to the Exolab Project
 *    (http://www.exolab.org/).
 *
 * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
 * ``AS IS"" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
 *
 * $Id: CommandLine.java,v 1.1 2004/11/26 01:51:02 tanderson Exp $
 *
 * Date         Author  Changes
 * 1/6/2000     jima    Created
 * 1/9/2000     jima    changed package name from com.ruware to org.exolab
 * 7/1/2000     jima    removed the CW prefix from the class name
 * 1/8/2001     jima    Removed it from jtf library and imported it into
 *                      the openjms library
 */

import java.util.Hashtable;
import java.util.Vector;

/**
 * This core class is responsible for processing the command line and
 * storing away the list of options and parameters specified. The
 * difference between an option and a command line is that an option
 * is a boolean value (true if it is specified and false otherwise)
 * and a parameter always has an associated value.
 *
 * @version     $version$
 * @author      jima
 **/
public class CommandLine {
    /**
     * A list of option of switches on the command line. A switch
     * is either set or not
     */
    private Vector _switches = new Vector();
    /**
     * A dictionary of all the options and their associated values
     */
    private Hashtable _options = new Hashtable();
    /**
     * Construct an instance of this class with the specified string
     * array.
     *
     * @param       args        command line argument
     */
    public CommandLine(String[] args) {
        processCommandLine(args);
    }
    /**
     * Default constructor which simply initialised the class
     */
    public CommandLine() {
    }
    /**
     * Check if the following option or command has been specified
     *
     * @param       name        name of option or command
     * @return      boolean     true if it has been specified
     */
    public boolean exists(String name) {
        return _switches.contains(name) || _options.containsKey(name);
    }
    /**
     * Check if the following option has been specified.
     *
     * @param       name        name of the option
     * @return      boolean     true if it has been specified
     */
    public boolean isSwitch(String name) {
        return _switches.contains(name);
    }
    /**
     * Check if the following parameter has been specified.
     *
     * @param       name        name of the parameter
     * @return      boolean     true if it has been specified
     */
    public boolean isParameter(String name) {
        return _options.containsKey(name);
    }
    /**
     * Return the value of the parameter or option. If the string nominates
     * an option then return null
     *
     * @param       name        name of option or parameter
     * @return      String      value of parameter or null
     */
    public String value(String name) {
        String result = null;
        if (_options.containsKey(name)) {
            result = (String) _options.get(name);
        }
        return result;
    }
    /**
     * Return the value of the parameter or option, returning a default
     * value if none is specified
     *
     * @param       name        name of option or parameter
     * @param       defaultValue the default value
     * @return      String      value of parameter
     */
    public String value(String name, String defaultValue) {
        String result = value(name);
        return (result != null) ? result : defaultValue;
    }
    /**
     * Add the following option or parameter to the list. An option will
     * have a null value, whereas a parameter will have a non-null value.
     * <p>
     * This will automatically overwrite the previous value, if one has been
     * specified.
     *
     * @param       name        name of option or parameter
     * @param       value       value of name
     * @return      boolean     true if it was successfully added
     */
    public boolean add(String name, String value) {
        return add(name, value, true);
    }
    /**
     * Add the following option or parameter to the list. An option will
     * have a null value, whereas a parameter will have a non-null value.
     * <p>
     * If the overwrite flag is true then this value will overwrite the
     * previous value. If the overwrite flag is false and the name already
     * exists then it will not overwrite it and the function will return
     * false. In all other circumstances it will return true.
     *
     * @param       name        name of option or parameter
     * @param       value       value of name
     * @param       overwrite   true to overwrite previous value
     * @return      boolean     true if it was successfully added
     */
    public boolean add(String name, String value, boolean overwrite) {
        boolean result = false;
        if (value == null) {
            // it is an option
            if ((_switches.contains(name)) &&
                (overwrite)) {
                _switches.addElement(name);
                result = true;
            } else if (!_switches.contains(name)) {
                _switches.addElement(name);
                result = true;
            }
        } else {
            // parameter
            if ((_options.containsKey(name)) &&
                (overwrite)) {
                _options.put(name, value);
                result = true;
            } else if (!_options.containsKey(name)) {
                _options.put(name, value);
                result = true;
            }
        }
        return result;
    }
    /**
     * This method processes the command line and extracts the list of
     * options and command lines. It doesn"t intepret the meaning of the
     * entities, which is left to the application.
     *
     * @param       args        command line as a collection of tokens
     */
    private void processCommandLine(String[] args) {
        boolean prev_was_hyphen = false;
        String prev_key = null;
        for (int index = 0; index < args.length; index++) {
            if (args[index].startsWith("-")) {
                // if the previous string started with a hyphen then
                // it was an option store store it, without the hyphen
                // in the _switches vector. Otherwise if the previous was
                // not a hyphen then store key and value in the _options
                // hashtable
                if (prev_was_hyphen) {
                    add(prev_key, null);
                }
                prev_key = args[index].substring(1);
                prev_was_hyphen = true;
                // check to see whether it is the last element in the
                // arg list. If it is then assume it is an option and
                // break the processing
                if (index == args.length - 1) {
                    add(prev_key, null);
                    break;
                }
            } else {
                // it does not start with a hyphen. If the prev_key is
                // not null then set the value to the prev_value.
                if (prev_key != null) {
                    add(prev_key, args[index]);
                    prev_key = null;
                }
                prev_was_hyphen = false;
            }
        }
    }
}





Read an int from Standard Input

 
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

import java.io.*;
/**
 * Read an int from Standard Input
 * @author  Ian F. Darwin, http://www.darwinsys.ru/
 * @version   $Id: ReadStdinInt.java,v 1.2 2004/02/08 23:57:29 ian Exp $
 */
public class ReadStdinInt {
  public static void main(String[] ap) {
    String line = null;
    int val = 0;
    try {
      BufferedReader is = new BufferedReader(
        new InputStreamReader(System.in));
      line = is.readLine();
      val = Integer.parseInt(line);
    } catch (NumberFormatException ex) {
      System.err.println("Not a valid number: " + line);
    } catch (IOException e) {
      System.err.println("Unexpected IO ERROR: " + e);
    }
    System.out.println("I read this number: " + val);
  }
}





Read an int from Standard Input, using 1.5

 
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

import java.util.Scanner;
/**
 * Read an int from Standard Input, using 1.5
 * @author  Ian F. Darwin, http://www.darwinsys.ru/
 * @version   $Id: ReadStdinInt15.java,v 1.2 2004/03/07 16:31:58 ian Exp $
 */
public class ReadStdinInt15 {
  public static void main(String[] ap) {
    int val;
    try {
      Scanner sc = Scanner.create(System.in);      // Requires J2SE 1.5
      val = sc.nextInt();
    } catch (NumberFormatException ex) {
      System.err.println("Not a valid number: " + ex);
      return;
    }
    System.out.println("I read this number: " + val);
  }
}





Read input from console

 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.ParseException;
public class ReadDoubleFromConsole {
  public static void main(String[] args) {
    System.out.println("Enter a number.");
    double numberFromConsole; 
    try {
      InputStreamReader isr = new InputStreamReader(System.in);
      BufferedReader br = new BufferedReader(isr);
      String s = br.readLine();
      DecimalFormat df = new DecimalFormat();
      Number n = df.parse(s);
      numberFromConsole = n.doubleValue();
    } catch (IOException e) {
      numberFromConsole = 0;
    } catch (ParseException e) {
      numberFromConsole = 0;
    }
    System.out.println(numberFromConsole );
  }
}





Show use of Argv to get an integer value from command line

 
/** Show use of Argv to get an integer value from command line */
public class AddException {
  /** Main program */
  public static void main(String[] argv) {
    int number = 0;
    System.out.println("The number of words in argv is " + argv.length);
    if (argv.length == 0) {
      number = 1234;
    } else if (argv.length == 1) {
      try {
        number = Integer.parseInt(argv[0]);
      } catch(NumberFormatException e) {
        System.err.println("Number " + argv[0] + " invalid (" + e.getMessage() + ").");
        System.exit(1);
      }
    } else {
      System.err.println("usage: UseArgv number");
      System.exit(1);
    }
    System.out.println("OK, number is " + number);
  }
}





SimpleCalc -- simple calculator using 1.5 java.util.Scanner

 
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Scanner;
import java.util.Stack;
/**
* SimpleCalc -- simple calculator using 1.5 java.util.Scanner
* @version  $Id: SimpleCalcScanner.java,v 1.3 2004/03/10 18:01:35 ian Exp $
*/
public class SimpleCalcScanner {
  /** The Scanner */
  protected  Scanner scan;
  /** The output */
  protected PrintWriter out = new PrintWriter(System.out);
  /** The variable name (not used in this version) */
  protected String variable;
  /** The operand stack */
  protected Stack s = new Stack();
  /* Driver - main program */
  public static void main(String[] av) throws IOException {
    if (av.length == 0)
      new SimpleCalcScanner(
        new InputStreamReader(System.in)).doCalc();
    else 
      for (int i=0; i<av.length; i++)
        new SimpleCalcScanner(av[i]).doCalc();
  }
  /** Construct a SimpleCalcScanner by name */
  public SimpleCalcScanner(String fileName) throws IOException {
    this(new FileReader(fileName));
  }
  /** Construct a SimpleCalcScanner from an open Reader */
  public SimpleCalcScanner(Reader rdr) throws IOException {
    scan = new Scanner(rdr);
    // Control the input character set:
    scan.slashSlashComments(true);  // treat "//" as comments
    scan.ordinaryChar("-");    // used for subtraction
    scan.ordinaryChar("/");  // used for division
  }
  /** Construct a SimpleCalcScanner from a Reader and a PrintWriter */
  public SimpleCalcScanner(Reader rdr, PrintWriter pw) throws IOException {
    this(rdr);
    setWriter(pw);
  }
  /** Change the output to go to a new PrintWriter */
  public void setWriter(PrintWriter pw) {
    out = pw;
  }
  protected void doCalc() throws IOException {
    int iType;
    double tmp;
    while (scan.hasNext()) {
      if (scan.hasNextDouble()) {
        push(scan.nextDouble());
      } else {
        String token = scan.next().toString();
        if (token.equals("+")) {
          // Found + operator, perform it immediately.
          push(pop() + pop());
        } else if (token.equals("-")) {
          // Found - operator, perform it (order matters).
          tmp = pop();
          push(pop() - tmp);
        } else if (token.equals("*")) {
          // Multiply is commutative
          push(pop() * pop());
        } else if (token.equals("/")) {
          // Handle division carefully: order matters!
          tmp = pop();
          push(pop() / tmp);
        } else if (token.equals("=")) {
          out.println(peek());
        } else {
          out.println("What"s this? " + token);
        }
      }
    }
  }
  void push(double val) {
    s.push(new Double(val));
  }
  double pop() {
    return ((Double)s.pop()).doubleValue();
  }
  double peek() {
    return ((Double)s.peek()).doubleValue();
  }
  void clearStack() {
    s.removeAllElements();
  }
}





Turn System.out into a PrintWriter

 
// : c12:ChangeSystemOut.java
// Turn System.out into a PrintWriter.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.PrintWriter;
public class ChangeSystemOut {
  public static void main(String[] args) {
    PrintWriter out = new PrintWriter(System.out, true);
    out.println("Hello, world");
  }
} ///:~





Utility class for printing aligned columns of text

  
/*
 * @(#)VMMetrics.java  1.3 04/01/05
 *
 * Copyright (c) 2000-2003 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
 * modify and redistribute this software in source and binary code form,
 * provided that i) this copyright notice and license appear on all copies of
 * the software; and ii) Licensee does not utilize the software in a manner
 * which is disparaging to Sun.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
 * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
 * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
 * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
 * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
 * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * This software is not designed or intended for use in on-line control of
 * aircraft, air traffic, aircraft navigation or aircraft communications; or in
 * the design, construction, operation or maintenance of any nuclear
 * facility. Licensee represents and warrants that it will not use or
 * redistribute the Software for such purposes.
 */
/*
 * @(#)MultiColumnPrinter.java  1.3 04/09/15
 *
 * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved
 * SUN PROPRIETARY/CONFIDENTIAL
 * Use is subject to license terms.
 *
 */
import java.util.Enumeration;
import java.util.Vector;
import java.util.Map;
import java.util.TreeMap;
import java.util.Iterator;
/**
 * Utility class for printing aligned collumns of text. How/where
 * the text is printed is determined by the abstract methods
 * doPrint(String) and doPrintln(String). The typical case is to 
 * create a subclass and make these methods print the string to standard 
 * out or error.
 * <P>
 * This class allows you to specify:
 * <UL>
 * <LI>The number of collumns in the output. This will determine
 * the dimension of the string arrays passed to add(String[])
 * or addTitle(String[]).
 * <LI>spacing/gap between columns
 * <LI>character to use for title border (null means no border)
 * <LI>column alignment. Only LEFT/CENTER is supported for now.
 * </UL>
 *
 * <P>
 * Example usage:
 * <PRE>
 *  MyPrinter  mp = new MyPrinter(3, 2, "-");
 *  String    oneRow[] = new String [ 3 ];
 *  oneRow[0] = "User Name";
 *  oneRow[1] = "Email Address";
 *  oneRow[2] = "Phone Number";
 *  mp.addTitle(oneRow);
 *
 *  oneRow[0] = "Bob";
 *  oneRow[1] = "bob@foo.ru";
 *  oneRow[2] = "123-4567";
 *  mp.add(oneRow);
 *
 *  oneRow[0] = "John";
 *  oneRow[1] = "john@foo.ru";
 *  oneRow[2] = "456-7890";
 *  mp.add(oneRow);
 *  mp.print();
 * </PRE>
 *
 * <P>
 * The above would print:
 * <P>
 * <PRE>
 *  --------------------------------------
 *  User Name  Email Address  Phone Number
 *  --------------------------------------
 *  Bob        bob@foo.ru    123-4567
 *  John       john@foo.ru   456-7890
 * </PRE>
 *
 *<P>
 * This class also supports multi-row titles and having title
 * strings spanning multiple collumns. Example usage:
 * <PRE>
 *     TestPrinter  tp = new TestPrinter(4, 2, "-");
 *     String    oneRow[] = new String [ 4 ];
 *     int[]    span = new int[ 4 ];
 *
 *     span[0] = 2; // spans 2 collumns
 *     span[1] = 0; // spans 0 collumns
 *     span[2] = 2; // spans 2 collumns
 *     span[3] = 0; // spans 0 collumns
 *
 *     tp.setTitleAlign(CENTER);
 *     oneRow[0] = "Name";
 *     oneRow[1] = "";
 *     oneRow[2] = "Contact";
 *     oneRow[3] = "";
 *     tp.addTitle(oneRow, span);
 * 
 *     oneRow[0] = "First";
 *     oneRow[1] = "Last";
 *     oneRow[2] = "Email";
 *     oneRow[3] = "Phone";
 *     tp.addTitle(oneRow);
 * 
 *     oneRow[0] = "Bob";
 *     oneRow[1] = "Jones";
 *     oneRow[2] = "bob@foo.ru";
 *     oneRow[3] = "123-4567";
 *     tp.add(oneRow);
 * 
 *     oneRow[0] = "John";
 *     oneRow[1] = "Doe";
 *     oneRow[2] = "john@foo.ru";
 *     oneRow[3] = "456-7890";
 *     tp.add(oneRow);
 * 
 *     tp.println();
 * </PRE>
 *
 * <P>
 * The above would print:
 * <P>
 * <PRE>
 *      ------------------------------------
 *          Name             Contact          
 *      First  Last      Email       Phone  
 *      ------------------------------------
 *      Bob    Jones  bob@foo.ru   123-4567
 *      John   Doe    john@foo.ru  456-7890
 * </PRE>
 *
 */
public abstract class MultiColumnPrinter {
    final public static int  LEFT  = 0;
    final public static int  CENTER  = 1;
    /*
     * Sets the default sorting behavior.
     * When set to true, the table entries are sorted unless otherwise
     * specified in a constructor.
     */
    final private static boolean  DEFAULT_SORT = true;
    private int numCol = 2;
    private int gap = 4;
    private int align = CENTER;
    private int titleAlign = CENTER;
    private String border = null;
    private Vector table = null;
    private Vector titleTable = null;
    private Vector titleSpanTable = null;
    private int curLength[];
    private boolean sortNeeded = DEFAULT_SORT;
    private int[] keyCriteria = null;
    /**
     * Creates a new MultiColumnPrinter class.
     *
     * @param numCol number of columns
     * @param gap gap between each column
     * @param border character used to frame the titles
     * @param align type of alignment within columns
     * @param sort true if the output is sorted; false otherwise
     *
     * REVISIT: Possibly adding another argument that specifies which ones can
     * be truncated (xxx...)
     */
    public MultiColumnPrinter(int numCol, int gap, String border, 
            int align, boolean sort) {
        table = new Vector();
        titleTable = new Vector();
        titleSpanTable = new Vector();
        curLength = new int[numCol];
        this.numCol = numCol;
        this.gap = gap;
        this.border = border;
        this.align = align;
        this.titleAlign = LEFT;
  this.sortNeeded = sort;
    }
    /**
     * Creates a new sorted MultiColumnPrinter class.
     *
     * @param numCol number of columns
     * @param gap gap between each column
     * @param border character used to frame the titles
     * @param align type of alignment within columns
     */
    public MultiColumnPrinter(int numCol, int gap, String border, int align) {
  this(numCol, gap, border, align, DEFAULT_SORT);
    }
    /**
     * Creates a sorted new MultiColumnPrinter class using LEFT alignment.
     *
     * @param numCol number of columns
     * @param gap gap between each column
     * @param border character used to frame the titles
     */
    public MultiColumnPrinter(int numCol, int gap, String border) {
  this(numCol, gap, border, LEFT);
    }
    /**
     * Creates a sorted new MultiColumnPrinter class using LEFT alignment
     * and with no title border.
     *
     * @param numCol number of columns
     * @param gap gap between each column
     */
    public MultiColumnPrinter(int numCol, int gap) {
  this(numCol, gap, null, LEFT);
    }
    /**
     * Adds to the row of strings to be used as the title for the table.
     *
     * @param row Array of strings to print in one row of title.
     */
    public void addTitle(String[] row) {
  if (row == null)
      return;
  int[] span = new int [ row.length ];
  for (int i = 0; i < row.length; i++) {
      span[i] = 1;
  }
  
  addTitle(row, span);
    }
    /**
     * Adds to the row of strings to be used as the title for the table.
     * Also allows for certain title strings to span multiple collumns
     * The span parameter is an array of integers which indicate how
     * many collumns the corresponding title string will occupy.
     * For a row that is 4 collumns wide, it is possible to have some 
     * title strings in a row to "span" multiple collumns:
     *
     * <P>
     * <PRE>
     * ------------------------------------
     *     Name             Contact          
     * First  Last      Email       Phone  
     * ------------------------------------
     * Bob    Jones  bob@foo.ru   123-4567
     * John   Doe    john@foo.ru  456-7890
     * </PRE>
     *
     * In the example above, the title row has a string "Name" that
     * spans 2 collumns. The string "Contact" also spans 2 collumns.
     * The above is done by passing in to addTitle() an array that
     * contains:
     *
     * <PRE>
     *    span[0] = 2; // spans 2 collumns
     *    span[1] = 0; // spans 0 collumns, ignore
     *    span[2] = 2; // spans 2 collumns
     *    span[3] = 0; // spans 0 collumns, ignore
     * </PRE>
     * <P>
     * A span value of 1 is the default.
     * The method addTitle(String[] row) basically does:
     *
     * <PRE>
     *   int[] span = new int [ row.length ];
     *   for (int i = 0; i < row.length; i++) {
     *       span[i] = 1;
     *   }
     *   addTitle(row, span);
     * </PRE>
     *
     * @param row Array of strings to print in one row of title.
     * @param span Array of integers that reflect the number of collumns
     * the corresponding title string will occupy.
     */
    public void addTitle(String[] row, int span[]) {
  // Need to create a new instance of it, otherwise the new values will
  // always overwrite the old values.
  String[] rowInstance = new String[(row.length)];
  for (int i = 0; i < row.length; i++) {
      rowInstance[i] = row[i];
  }
  titleTable.addElement(rowInstance);
  titleSpanTable.addElement(span);
    }
    /**
     * Set alignment for title strings
     *
     * @param titleAlign
     */
    public void setTitleAlign(int titleAlign)  {
  this.titleAlign = titleAlign;
    }
    /**
     * Adds one row of text to output.
     *
     * @param row Array of strings to print in one row.
     */
    public void add(String[] row) {
  // Need to create a new instance of it, otherwise the new values will
  // always overwrite the old values.
  String[] rowInstance = new String[(row.length)];
  for (int i = 0; i < row.length; i++) {
      rowInstance[i] = row[i];
  }
  table.addElement(rowInstance);
    }
    /**
     * Clears title strings.
     */
    public void clearTitle()  {
  titleTable.clear();
  titleSpanTable.clear();
    }
    /**
     * Clears strings.
     */
    public void clear()  {
  table.clear();
  if (curLength != null)  {
            for (int i = 0; i < curLength.length; ++i)  {
                curLength[i] = 0;
            }
        }
    }
    /**
     * Prints the multi-column table, including the title.
     */
    public void print() {
  print(true);
    }
    /**
     * Prints the multi-column table.
     * 
     * @param printTitle Specifies if the title rows should be printed.
     */
    public void print(boolean printTitle) {
    // REVISIT:
    // Make sure you take care of curLength and row being null value cases.

  // Get the longest string for each column and store in curLength[]
  // Scan through title rows
  Enumeration elm = titleTable.elements();
  Enumeration spanEnum = titleSpanTable.elements();
  int rowNum = 0;
  while (elm.hasMoreElements()) {
      String[] row = (String[])elm.nextElement();
      int[] curSpan = (int[])spanEnum.nextElement();
      for (int i = 0; i < numCol; i++) {
    // Fix for 4627901: NullPtrException seen when 
    // execute "jmqcmd list dur"
    // This happens when a field to be listed is null.
    // None of the fields should be null, but if it
    // happens to be so, replace it with "-".
                if (row[i] == null) 
                    row[i] = "-";
    int len = row[i].length();
    /*
     * If a title string spans multiple collumns, then
     * the space it occupies in each collumn is at most
     * len/span (since we have gap to take into account
     * as well).
     */
    int span = curSpan[i], rem = 0;
    if (span > 1)  {
        rem = len % span;
        len = len/span;
    }
    if (curLength[i] < len)  {
        curLength[i] = len;
        if ((span > 1) && ((i+span) <= numCol))  {
          for (int j=i+1; j<(i+span); ++j)  {
          curLength[j] = len;
      }
      /*
       * Add remainder to last collumn in span
       * to avoid round-off errors.
       */
      curLength[(i+span)-1] += rem;
        }
    }
      }
      ++rowNum;
  }
  // Scan through rest of rows
  elm = table.elements();
  while (elm.hasMoreElements()) {
      String[] row = (String[])elm.nextElement();
      for (int i = 0; i < numCol; i++) {
                // Fix for 4627901: NullPtrException seen when 
                // execute "jmqcmd list dur"
                // This happens when a field to be listed is null.
                // None of the fields should be null, but if it
                // happens to be so, replace it with "-".
                if (row[i] == null) 
                    row[i] = "-";
    if (curLength[i] < row[i].length())
        curLength[i] = row[i].length();
      }
  }
  /*
   * Print title
   */
  if (printTitle)  {
      printBorder();
      elm = titleTable.elements();
      spanEnum = titleSpanTable.elements();
      while (elm.hasMoreElements()) {
          String[] row = (String[])elm.nextElement();
          int[] curSpan = (int[])spanEnum.nextElement();
          for (int i = 0; i < numCol; i++) {
        int availableSpace = 0, span = curSpan[i];
        if (span == 0)
      continue;
        availableSpace = curLength[i];
        if ((span > 1) && ((i+span) <= numCol))  {
          for (int j=i+1; j<(i+span); ++j)  {
              availableSpace += gap;
              availableSpace += curLength[j];
          }
        }
        if (titleAlign == CENTER)  {
            int space_before, space_after;
            space_before = (availableSpace-row[i].length())/2;
            space_after = availableSpace-row[i].length() - space_before;
            printSpaces(space_before);
                  doPrint(row[i]);
            printSpaces(space_after);
            if (i < numCol-1) printSpaces(gap);
        } else  {
                  doPrint(row[i]);
            if (i < numCol-1) printSpaces(availableSpace-row[i].length()+gap);
        }
          }
          doPrintln("");
      }
      printBorder();
  }
  if (sortNeeded)
      printSortedTable();
  else
      printUnsortedTable();
    }
    /*
     * Prints the table entries in the sorted order.
     */
    private void printSortedTable() {
  // Sort the table entries
        TreeMap sortedTable = new TreeMap();
        Enumeration elm = table.elements();
        while (elm.hasMoreElements()) {
            String[] row = (String[])elm.nextElement();
      // If keyCriteria contains valid info use that
      // to create the key; otherwise, use the default row[0]
      // for the key.
      if (keyCriteria != null && keyCriteria.length > 0) {
    String key = getKey(row);
    if (key != null)
                   sortedTable.put(key, row);
    else
                   sortedTable.put(row[0], row);
      } else {  
                sortedTable.put(row[0], row);
      }
        }
  // Iterate through the table entries
        Iterator iterator = sortedTable.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry)iterator.next();
            String[] row = ((String[])entry.getValue());
      printRow(row);
  }
    }
    /*
     * Creates the key for the current row based on the
     * criteria specified by setKeyCriteria().
     * If key cannot be created by the criteria, it simply returns
     * null.
     *
     * Examples:
     * String[] row = {"foo", "bar", "hello");
     *
     * int[] keyCriteria = {0};
     * key = "foo";
     *
     * int[] keyCriteria = {0, 1};
     * key = "foobar";
     *
     * int[] keyCriteria = {2, 1};
     * key = "hellobar";
     *
     * int[] keyCriteria = {4};
     * key = null;
     */
    private String getKey(String[] row) {
  String key = "";
  
  for (int i = 0; i < keyCriteria.length; i++) {
      int content = keyCriteria[i];
      try {
          key = key + row[content];
      } catch (ArrayIndexOutOfBoundsException ae) {
    // Happens when keyCriteria[] contains an index that
     // does not exist in "row".
    return null;
      }
  }
  return key;
    }
    /*
     * Prints the table entries in the order they were entered.
     */
    private void printUnsortedTable() {
        Enumeration elm = table.elements();
        while (elm.hasMoreElements()) {
            String[] row = (String[])elm.nextElement();
      printRow(row);
        }
    }
    private void printRow(String[] row) {
            for (int i = 0; i < numCol; i++) {
                    if (align == CENTER)  {
                        int space1, space2;
                        space1 = (curLength[i]-row[i].length())/2;
                        space2 = curLength[i]-row[i].length() - space1;
                        printSpaces(space1);
                        doPrint(row[i]);
                        printSpaces(space2);
                        if (i < numCol-1) printSpaces(gap);
                    } else  {
                        doPrint(row[i]);
                        if (i < numCol-1) printSpaces(curLength[i]-row[i].length()+gap);
                    }
            }
            doPrintln("");
    }
    /**
     * Prints the multi-column table, with a carriage return.
     */
    public void println() {
  print();
  doPrintln("");
    }
    private void printSpaces(int count)  {
        for (int i = 0; i < count; ++i)  {
            doPrint(" ");
        }
    }
    private void printBorder() {
  int colNum = 1;
  if (border == null) return;
  // For the value in each column
  for (int i = 0; i < numCol; i++) {
      for (int j = 0; j < curLength[i]; j++) {
                doPrint(border);
      }  
  }
  // For the gap between each column
  for (int i = 0; i < numCol-1; i++) {
      for (int j = 0; j < gap; j++) {
                doPrint(border);
      }  
  }
  doPrintln("");
    }
    /*
     * Sets the criteria for the key.
     * new int[] {0, 1} means use the first and the second
     * elements of the array.
     */
    public void setKeyCriteria(int[] criteria) {
  this.keyCriteria = criteria;
    }
    /**
     * Method that does the actual printing. Override this method to
     * print to your destination of choice (stdout, stream, etc).
     *
     * @param str String to print.
     */
    public abstract void doPrint(String str);
    /**
     * Method that does the actual printing. Override this method to
     * print to your destination of choice (stdout, stream, etc).
     *
     * This method also prints a newline at the end of the string.
     *
     * @param str String to print.
     */
    public abstract void doPrintln(String str);
}





VarArgsDemo - show 1.5 variable arguments

 
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

import java.io.PrintStream;
import java.util.Date;
/**
 * VarArgsDemo - show 1.5 variable arguments
 * 
 * @author ian
 * @version $Id: VarArgsDemo.java,v 1.1 2004/03/07 16:35:13 ian Exp $
 */
public class VarArgsDemo {
  public static void main(String[] args) {
    process(System.out, "Hello", "Goodbye");
    process(System.out, 42, 1066, 1776);
    process(System.out, "Foo", new Date(), new Object());
  }
  static void process(PrintStream out, Object ... args) {
    line();
    for (int i = 0; i < args.length; i++){
      out.println("Argument " + i + " is " + args[i]);
    }
  }
  static void process(PrintStream out, int ... args) {
    for (int i = 0; i < args.length; i++){
      out.println("Argument " + i + " is " + args[i]);
    }
  }
  private static void line() {
    System.out.println("--------------------------");
  }
}