1

I need to add values into an int array.

    int[] placeHolders[];

Now i do not know the size of the elements to add into this array. I add it while i have input. I want to know how can i convert my string output values into int array repeatedly.

Input: 23.45.1.34

I am using string tokenize on . to get tokens

Value = Integer.parseInt(strtokObject.nextElement().toString());

I am using above line to add int to single int value but if i need to add int elements to array just like push in vector (C++ STL) i am unable to do.

2
  • 1
    in fact you can't push elements in java arrays, use Lists/ArrayLists instead. Also by using string.split(".") you'll get an array of strings representing your numbers Commented Sep 20, 2012 at 7:44
  • 1
    Use an ArrayList rather than a normal array decliration. Commented Sep 20, 2012 at 7:44

5 Answers 5

5
String str = "23.45.1.34";
String sarr = str.split("\\.");
int[] result = new int[sarr.length];
for (int i = 0;  i < sarr.length;  i++) {
    result[i] = Integer.parseInt(s);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Using: ArrayList<Integer> placeHolders; int value = Integer.parseInt(strtokObject.nextElement().toString()); cageObject.placeHolders.add(value); Still getting errorsException: java.lang.NullPointerException
2

When you don't know the size of a data set to be stored in an array, you should use an implementation of java.util.List<E> such as ArrayList.

ArrayList<Integer> placeHolderList = new ArrayList<Integer>();
int value = Integer.parseInt(strtokObject.nextElement().toString());
placeHolderList.add(value); // adds the int to the underlying array

You can then use List#toArray to convert your list into an array if necessary.

Comments

2

I'd use myString.split("\\.") to return a String[], create an equal size int[], then parse each String to an int rather than use a tokenizer. Also you could know the size of placeHolders by counting '.'s in the string (e.g., myString.replaceAll("[^\\.]", "").length()) (obviously add one to that number).

Comments

1

I assume your input string is input.

So you can do something like this:

String[] inputStrs = input.split("\\.");

and

//Do a while loop
placeholder[i] = Integer.ParseIne(inputStrs[i]);

1 Comment

Make sure you escape that '.' (\\.), otherwise you'll be splitting on EVERY character (String.split() takes a regular expression).
0

You can use ArrayList<Integer> which is similar to vector in c++. add to it using aList.add(num);

if you want an array you can at the end use the toArray method.

Integer[] arr = aList.toArray(new Integer[0]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.