Reputation:
I have a text stream that only contains integers each seperated by a comma. here is an example of what I have:
String text="143,136,159,140";
I need to extract every number one by one. I tried something like that.
int placeHolder=0;
for(int i=0;i<text.length();i++) {
if(text.charAt(i)==',')
{
System.out.println(text.substring(placeHolder,i));
placeHolder=i+1;
}
}
The output has to be like this :
143
136
159
140
but I am getting this instead :
143
136
159
I couldn't manage to get last one.what is it that I m doing wrong
Upvotes: 0
Views: 86
Reputation: 18480
You code don't print the last number because you only print when found ,
. So for last number you don't do anything.
You need to add this line after for loop to print last number
System.out.println(text.substring(placeHolder));
Rather you can try this way to print inside the loop
int placeHolder=0;
for(int i=0;i<text.length();i++) {
if(i == text.length()-1 || text.charAt(i+1)==',' )
{
System.out.println(text.substring(placeHolder,i+1));
placeHolder=i+2;
}
}
Or you can use .split()
String[] nums = text.split(",");
for (String num : nums) {
System.out.println(num);
}
Upvotes: 1
Reputation: 734
Because, the code checks for a ',' and prints the integer before it. But there is no ',' after the last integer, so it is not printed. Instead, use text.split(",");
Upvotes: 0
Reputation: 522752
Using streams, we can try:
String text = "143,136,159,140";
List<Integer> nums = Arrays.stream(text.split(","))
.map(Integer::valueOf)
.collect(Collectors.toList());
Upvotes: 0
Reputation: 984
You can use split(",") like this:
String[] numbers = text.split(",");
for (String number : numbers) {
System.out.println(number);
}
Upvotes: 0