Hi, I've been having trouble understanding this code that my professor put on the web. Can someone help me understand this. I thought this would compile and run but its giving me an error message
" Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at fileio.AllCapsDemo.main(AllCapsDemo.java:64) "
Im not sure how i can fix this problem and actually run this program.

package fileio;
import java.io.*;

class AllCaps
{
    String sourceName;
    AllCaps(String sourceArg)
    {
        sourceName = sourceArg;
    }
    void convert()
    {
        try
        {   // Create file objects
            File source = new File(sourceName);
            File temp = new File("cap" + sourceName + ".tmp");
            // Create input stream
            FileReader fr = new FileReader(source);
            BufferedReader in = new BufferedReader(fr);
            // Create output stream
            FileWriter fw = new FileWriter(temp);
            BufferedWriter out = new BufferedWriter(fw);
            boolean eof = false;
            int inChar = 0;
            do {
                inChar = in.read();
                if (inChar != -1)
                {
                    char outChar = Character.toUpperCase( (char)inChar );
                    out.write(outChar);
                } else
                    eof = true;
            } while (!eof);
            in.close();
            out.close();

            boolean deleted = source.delete();
            if (deleted)
                temp.renameTo(source);
        } catch (IOException e)
        {
            System.out.println("Error -- " + e.toString());
        } catch (SecurityException se)
        {
            System.out.println("Error -- " + se.toString());
        }
    }
}
public class AllCapsDemo
{
    public static void main(String[] args)
    {
        AllCaps cap = new AllCaps(args[0]);
        /*
         * Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
         * at fileio.AllCapsDemo.main(AllCapsDemo.java:53)
         */
         cap.convert();
    }
}

Make sure you are passing some arguments to the program (and the main method).
It looks like the args array is empty and accessing the args[0] would throw an exception.
You can pass the path to a file by calling the program as follows from the shell (command line):

$ java AllCapsDemo somefile.txt

Or, you can fix the code to check for empty args array.

public class AllCapsDemo
{
    public static void main(String[] args)
    {
        if (args.length < 1) {
            System.out.println("No arguments passed.");
            return;
        }
        AllCaps cap = new AllCaps(args[0]);
        cap.convert();
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.