Alamin
Alamin

Reputation: 43

Needed help loading in a file into a java program

I'm trying to load in the file called, Tut16_ReadText.txt and make it run through the program to output if its heavy or light.

I get the error which i pasted down below. I can't get arround to make this program work. Can anyone explain what i have to do to make this program work?

Thank you,

import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;


    public class test1 {
        public static void main(String args[]) throws Exception {
            if (args.length != 1) {
                System.out.println("usage: Tut16_ReadText file1");

            }
            BufferedReader br = null;
            try {
                br = new BufferedReader(new FileReader("F:/Programming/Java/Week16/Tut16_ReadText.txt"));

                String sCurrentLine;
                int totalwords = 0, totalchar = 0;
                while ((sCurrentLine = br.readLine()) != null) {
                    String words[] = sCurrentLine.split(" ");
                    totalwords += words.length;
                    for (int j = 0; j < words.length; j++) {
                        totalchar += words[j].length();
                    }
                }

                double density = (1.0 * totalchar) / totalwords;
                if (totalchar > 0) {
                    System.out.print(args[0] + " : " + density + " : ");
                    if (density > 6.0) 
                        System.out.println("heavy");
                    else
                        System.out.println("light");
                } else
                    System.out.println("This is an error - denisty of zero.");
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (br != null)br.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

usage: Tut16_ReadText file1 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at test1.main(test1.java:28)

Upvotes: 1

Views: 52

Answers (1)

Henry
Henry

Reputation: 337

You're trying to access an index of array 'args' that does not exist.

This line:

System.out.print(args[0] + " : " + density + " : ");

is accessing args[0] which needs to be provided when you run the program.

Try using

java test1 yourinputparameter

To run the program and it should work.

Also; in these lines at the beginning of your program:

        if (args.length != 1) {
            System.out.println("usage: Tut16_ReadText file1");

        }

You should add a

System.exit(0);

So that the rest of the program does not run if the incorrect amount of parameters is entered.

Upvotes: 1

Related Questions