Notes for Project 2

Command-line arguments

Here's a simple program that works with command-line arguments:

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

Here's an example of running the PizzaOrder program. The dollar sign is the prompt in the command window.
$ java PizzaOrder1 pepperoni cheese mushrooms
3 toppings:

Using Scanner to read from a text file

This program shows how to read from a text file using a Scanner:

import java.util.*;

public class ReadText {
   public static void main(String[] args) {
      Scanner fin = null;
      try {
         fin = new Scanner(new File("myFile.txt"));
      } catch (FileNotFoundException x) {
         System.out.println("File open failed.");
         System.exit(0);   // TERMINATE THE PROGRAM

      String line;
      while (fin.hasNextLine()) {
         line = fin.nextLine();

Note that the exception handling for opening a file is required and the program won't compile without catching or declaring the exception. We'll talk about this more in the next few weeks.

Also note that the variable fin has to be declared outside of the try block if it's going to be used outside of the try block.