Reputation: 15
I writing a program that takes a string inputted by user. (example: 175-24-56-5) The program takes that string and puts it in an ArrayList. The problem I'm having is that when I try to print the ArrayList, the last number (that should be in the ArrayList) isn't printed.
Here's my code for that method:
public void dc(String txt) {
ArrayList<String> unkey = new ArrayList<String>();
int l = txt.length();
int x = 0;
String xx = "";
String k = "";
for (int j = l; j > 0; j--) {
xx = Character.toString(txt.charAt(x));
System.out.println(xx);
if (xx.equals("-")) {
unkey.add(k);
k = "";
} else {
k += xx;
}
x++;
}
System.out.println(l);
System.out.println(unkey);
System.out.println(x);
}
It should have printed
{175, 24, 56, 5}
But it only prints
{175, 24, 56}
I'm relatively new to this. Any help? Thanks in advance..
Upvotes: 0
Views: 949
Reputation: 37023
Your issues is with for loop condition where you are missing 0th element. So your for-loop condition should be >= 0
and start with l-1
Instead of parsing string character by character, you could use the following:
String[] numbers = txt.split("-");//Using List<String> stringList = Arrays.asList(number); you can convert to list.
for (int i =0; i< numbers.length(); i++) {
System.out.println(numbers[i]);
}
Upvotes: 2
Reputation: 650
for (int j = l; j > 0; j--)
this line should be changed to
for(int j=l-1; j>=0; j--)
For your specific example (175-24-56-5) are stored in the index order of (0-1-2-3) not (1-2-3-4).
Hope it helps
Upvotes: 0
Reputation: 754
Add
unkey.add(k);
after cycle. You add numbers only when you found '-' now.
Upvotes: 0
Reputation: 2432
Change >
to >=
so you're not leaving out the 1st element:
for (int j = l; j >= 0; j--)
Upvotes: 0
Reputation: 23171
The array starts with index 0 so your for loop needs to be:
for (int j = l; j >= 0; j--) {
Though you could simplify this whole thing by using "split":
String[] nums = txt.split("-");
ArrayList<String> unkey = Arrays.asList(nums);
Upvotes: 0