Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String[] args. to int/double in java?

Tags:

java

I'm trying to convert a main programs "String[] args" into 5 ints, and 4 doubles. (i know it's kind of confusing)

The way i was thinking of doing it was having a forreach loop to loop through String args[] and add them to an int array (for the first 5), however i had to use for the array, so it doesn't work.

if (args != null) {
        // If arguments where given, use the arguments and run the program
        // NEED TO SOMEHOW CONVERT ARGS INTO INTEGER FORM AFTER BEING PASSED IN
        ArrayList<Integer> valArr = new ArrayList<Integer>(10); // could be 9
        for (String val : args) {
            // Parse the string and add it to valArray
            int temp = Integer.parseInt(val);
            valArr.add(temp);
        }   

        CarPark cp = new CarPark(valArr[0], valArr[1], valArr[2], valArr[3]);   

this is what i'm looking at at the moment... am i completely wrong? or close?

like image 787
joelwmale Avatar asked Oct 20 '22 08:10

joelwmale


1 Answers

Just parse it with two indexing for loops.

int[] myInts = new int[5];
double[] myDoubles = new double[4];

// Initialize these arrays with "defaults" here.

// Notice how we handle the possibility of the user not entering enough values.
for (int i = 0; i < Math.min(5, args.length); i++)
    myInts[i] = Integer.parseInt(args[i]);

for (int i = 0; i < Math.min(4, args.length - 5); i++)
    myDoubles[i] = Double.parseDouble(args[i+5]);

CarPark cp = new CarPark(myInts[0], myInts[1], myInts[2], myInts[3]);   
like image 168
merlin2011 Avatar answered Oct 23 '22 02:10

merlin2011