user3339618
user3339618

Reputation: 25

How to assign variables in a string?

I need to assign variables in a string.

 String s = "102, 145, 163, 124";

I want to assign a separate variable like below;

num1 = 102;
num2 = 145;
num3 = 163;
num4 = 124;

I need to do it programatically since the values will change and increase so whatever is in string s is assigned a variable. Thanks

Upvotes: 0

Views: 397

Answers (4)

Michael Yaworski
Michael Yaworski

Reputation: 13483

Because there are a dynamic number of values, you need to use an array (or ArrayList):

String s = "102, 145, 163, 124";

String[] nums = s.split(", ");

// just printing the array
for (int i = 0; i < nums.length; i++) {
    System.out.println(nums[i]);
}

Output of that:

102
145
163
124

Upvotes: 1

Cruceo
Cruceo

Reputation: 6834

If the values are going to change, you should look into using an ArrayList which will be dynamic and vary with the length of your data.

For instance, you could easily convert all that data to an ArrayList like this:

String string = "102, 145, 163, 124";
ArrayList<Integer> list = new ArrayList<Integer>();
for(String s : string.split(",")) list.add(Integer.parseInt(s.trim())); 

Each item would then be accessible by calling it's index like so:

int num0 = list.get(0);
int last = list.get(list.size() - 1);

Storing data in lists is a dynamic approach that's scale-able.

Upvotes: 2

GhostDerfel
GhostDerfel

Reputation: 1551

Try to split then parse your strings

String s = "102, 145, 163, 124";
String[] sArray = s.split(",");
List<Integer> integers = new ArrayList<Integer>();
for(String item:sArray){
  integers.add(Integer.parseInt(s.replace(",","")));
}

Upvotes: 0

a person
a person

Reputation: 986

StringTokenizer tokenizer = new StringTokenizer(s, ", ");
for (int i = 0; i < tokenizer.countTokens(); i++)

Upvotes: 0

Related Questions