简体   繁体   中英

How to input a list of numbers and assign it to a variable

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.

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]);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM