0

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

niculare
  • 3,629
  • 1
  • 25
  • 39

3 Answers3

0

Well in most programming languages (since no language was given) a string can already be used as an array

 var str = "hellp";
 print str[0];

This would print out "h". If you were to use a function for counting than it would count the amount in the array. Such as PHP = count() or javascript = .length

EDIT JAVA

Im not sure how regexp works in Java, but Try this

String s = "321351";
int charCount = s.replaceAll("\[^0-9]\", "").length();
println(charCount);

This link might be helpful Java: How do I count the number of occurrences of a char in a String?

Community
  • 1
  • 1
Juan Gonzales
  • 1,967
  • 2
  • 22
  • 36
  • I wanted to avoid using string because I'm making an int array and using string may cause error on catching the right value of the integer. such as, "34 2 13" would be terrifying to convert to {34,2,13}. – user2153204 Mar 10 '13 at 06:48
  • so you want to catch each individual int in the input value not groupings? – Juan Gonzales Mar 10 '13 at 06:51
  • yes, i need to have the individual values of the int and i will have to be able to count the number of ints user inputs. – user2153204 Mar 10 '13 at 06:55
0

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'.
niculare
  • 3,629
  • 1
  • 25
  • 39
0
Scanner sc = new Scanner(System.in);
        StringTokenizer stringTokenizer = new StringTokenizer(sc.nextLine(), " ");
        int[] result = new int[stringTokenizer.countTokens()];
        int i = 0;
        while (stringTokenizer.hasMoreTokens()){
            result[i] = Integer.parseInt(stringTokenizer.nextToken());
            System.out.println(result[i++]);
}

Use above code to handle extra spaces given by user input. Like below string :

' 1 2 3 4 5 6 '

Nitul
  • 997
  • 12
  • 35