javaargscmdline-args

Creating new Object from args given through cmd line gives me OutOfMemoryError thrown from UncaughtExceptionhandler


I cannot find out why the above error thrown. It works fine when I only enter 2 arguments (e.G 22.5 km), using more than that (20.5 km 400 ft) gives the error.

Here is the code:

if (args.length > 0)
{            
    for (int i = 0; i < args.length; i = +2)
    {
        lengthsCollection.add(new Length(Double.parseDouble(args[i]), args[i+1]));    
    }
}

class Length is working fine everywhere else

public class Length {
    private double valueM;
    private String unitM;

    public Length(double value, String unit)  
    {
        this.valueM = value;
        this.unitM = unit;
    }

Can someone help me out? I thought my code should work if the user inputs properly (length + unit pairs)


Solution

  • This iteration:

     for (int i = 0; i < args.length; i = +2)
    

    is executed for ever when args.length > 2 because i remains 2 for ever. Hence the memory error.

    What you need is:

    for (int i = 0; i < args.length; i += 2)