Search code examples
javaarraysenter

(java)set length of an array depending on the number of values from input?


I'm trying to set the length of an array depending on the user's input without asking for a key to end the array. for example, when the user types "3 2 4", my array would be {3,2,4}. and if the user types "1", then the array would be {1}. the length of the array would vary only on the user's input. I'm trying to see if the enter key can be the trigger to end taking values but i'd really like some help on this. thanks in advance


Solution

  • If you are using Java try this (assuming that the numbers are separated by space):

    Scanner sc = new Scanner(System.in);
    String[] tokens = sc.nextLine().split(" ");
    int[] result = new int[tokens.length];
    int i = 0;
    for (String token : tokens)
        result[i++] = Integer.parseInt(token);
    // here you will have de desired array stored in the variable 'result'.