Intro. to Programming Workshop - 6

Welcome back to the Intro. to Programming Workshops! This week's workshop will focus on File IO and Exceptions!
The PokeVentures game code now includes external asset usage and some attack animations!

Resources

Summary

Files

Useful classes for dealing with Files:

  • File - For creating new files, like "Pokemon.txt"
  • Scanner - For reading file input
  • PrintWriter - For producing file output
  • FileWriter - Convenient combination of File and PrintWriter

Exceptions

Example code for throwing an Exception with a custom message:

import java.io.*;  
import java.util.Scanner;

public class Demo {  
    public static void main(String[] args) {

        // Grab input from keyboard
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a command: ");
        String input = sc.nextLine();

        try {

            if (input.trim().equalsIgnoreCase("run")) {
                // Note the use 'throw' and not 'throws'
                throw new Exception("HAH! Just kidding!");
            } else {
                System.out.println("Okay .....");
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        System.out.println("Exiting program.");
    }
}

Case 1: Output of the program when input is " RuN ":

Please enter a command:  
  RuN 
HAH! Just kidding!  
Exiting program.  

Case 2: Output of the program when input is "Get to tha choppa!"

Please enter a command:  
Get to tha choppa!  
Okay .....  
Exiting program.