Click to See Complete Forum and Search --> : Trouble Understanding this Java Code?


CMSHelper
05-24-2010, 02:21 AM
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.

Java Syntax (Toggle Plain Text)
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();
}
}

sohguanh
05-24-2010, 04:41 AM
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.

The program compiles ok but when you execute it is expecting a command line argument. That argument is a text file containing all the lower-case letters. After run finish, the same file would have all it's contents change to upper-case letters.

javac fileio/AllCapsDemo.java
java fileio.AllCapsDemo <argument in here>

Say we prepare a file called test with lower-case letters inside. We execute like java fileio.AllCapsDemo test

The text file called test will contain all the upper-case letters inside.