0

Below is the script i wrote to attempt to input a list of numbers(integers) and assign it to a variable

import java.util.ArrayList;   
import java.util.Arrays;

public class AssignList
{
    public static void main(String[] args)    
    {   
      //int[] b =Arrays.toString(args);     //my attempt to assign an input to variable b
      System.out.println(Arrays.toString(args)); 

         int[] a = {5, 2, 4, 1};            //how to print out integers
         System.out.println(Arrays.toString(a));  
     }
}

i can input and print out a list of numbers but i haven't been able to figure out how to assign it to a variable.


I dont mean my question is necessarily different from the one linked by the commenter, it's just i havent been able to figure it out even after looking at it.

I think the format of args is java.lang.String. Assuming that one will execute the script by typing java AssignList 5241, i would like to be able to assign the input 5241 as an array so that i can pick out each element by indexing.

stratofortress
  • 453
  • 1
  • 9
  • 21
  • 2
    Possible duplicate of [Converting String Array to an Integer Array](http://stackoverflow.com/questions/18838781/converting-string-array-to-an-integer-array) – resueman Mar 01 '16 at 20:21
  • "java AssignList 5241" -> the args received in main is a string array with exactly one entry: "5241". If you want each digit to be separated you have to suppliy it by "java AssignList 5 2 4 1" (note the spaces), so the args param contains four entries. Afterwards you can convert each (String) entry into an int. – Heri Mar 01 '16 at 21:54

1 Answers1

1

args is a String array. If you write "java AssignList 5241" you will have one element "5241" in your array, you can access this element by args[0]

If you write "java AssignList 5 2 4 1" you will have 4 elements in your array. You can convert a String array to a int array by converting every single element.

So if you use "java AssignList 5 2 4 1"

    int[] intArray = new int[args.length];
    for (int i =0;i<intArray.length;i++){
        intArray[i]=Integer.parseInt(args[i]);
    }

And if you use "java AssignList 5241"

    String arg = args[0];
    String[] argsArray = arg.split("");
    int[] intArray = new int[argsArray.length];
    for (int i =0;i<intArray.length;i++){
        intArray[i]=Integer.parseInt(argsArray[i]);
    }
Fabich
  • 2,768
  • 3
  • 30
  • 44