user3078337
user3078337

Reputation: 41

Eclipse Commandline Arguments with String[] args

I need to enter a String input, format it, and display the output in a certain format. I'm supposed to use the Run > Run Configuration > Arguments > Program Argument and I entered in any string (ie. "test") in the Program arguments section. When I try to run the java application, I keep getting an error message in the Console window. How do I use the Commandline arguments? What should I enter in the program arguments? Any help with this, would be greatly appreciated. Thanks.

Below is the error message that I get in the Console window:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at a00752124.data.InventoryReader.read(InventoryReader.java:26)
    at a00752124.Lab2.<init>(Lab2.java:38)
    at a00752124.Lab2.main(Lab2.java:28)

Below is my sourcecode for the main class:

public class Lab2 {

    /**
     * Main method of Lab2 class
     * 
     * @param args
     */
    public static void main(String[] args) {
        new Lab2(args[0]);
    }

    /**
     * Constructor for Lab2 class
     * 
     * @param itemCount
     */
    public Lab2(String itemCount) {

        Item[] items = InventoryReader.read(itemCount);

        System.out.println(Arrays.toString(items));

        InventoryReport.display(items);
        }

    }

Here's the source code for my InventoryReader's read method:

public static Item[] read(String input) {
        String[] rows = input.split(":");
        Item[] items = new Item[rows.length];

        int i = 0;
        for (String row : rows) {

            String[] element = row.split("\\|");
            items[i] = new Item(element[0], element[1], Integer.valueOf(element[2]), Float.valueOf(element[3]));
            i++;


        }

        return items;
    }

Upvotes: 0

Views: 896

Answers (1)

PM 77-1
PM 77-1

Reputation: 13334

You have:

String row = "";

then:

String[] element = row.split("\\|");

What is the size of element after you split an empty string?

Right after you assume that element has at least 4 items.

items[i] = new Item(element[0], element[1], Double.valueOf(element[2]), Double.valueOf(element[3]));

Clear enough?

Upvotes: 2

Related Questions