Reputation: 143
I have been trying to convert a JavaScript function to a Java method, whereby a number is passed by argument and if two concurrent numbers are even a dash "-" would be placed between them.
This works fine as long as the last digit is not even, if it is even I get an out of bounds error which I'm assuming is to do with the if statement using arr2.get(i + 1)
where the first part of the condition is true
but the second can not be met due to reaching the end of the list. Is there an easy way to correct the logic here?
I am fairly new to Java and struggling with some problems I can solve easily in JavaScript due to how some of the data stuctures act differently.
public void dash(int someNumber) {
int num = someNumber;
String str = String.valueOf(num);
String arr1[] = str.split("");
String result = "";
ArrayList<Integer> arr2 = new ArrayList<Integer>();
for (int i = 0; i < arr1.length; i++) {
int temp = Integer.parseInt(arr1[i]);
arr2.add(temp);
}
for(int i = 0; i < arr2.size(); i++) {
if (arr2.get(i) % 2 == 0 && arr2.get(i + 1) % 2 == 0) {
result = result + arr2.get(i) + "-";
}
else{
result = result + arr2.get(i);
}
}
System.out.println(result);
}
}
And the main
.
public class mainController {
public static void main(String[] args) {
DashSort ds = new DashSort();
ds.dash(245461);
}
}
Changed if statment to this and seems to work fine.
if (i + 1 == arr2.size()) {
result = result + arr2.get(i);
}
else if (arr2.get(i) % 2 == 0 && i < arr2.size() && arr2.get(i + 1) % 2 ==0) {
result = result + arr2.get(i) + "-";
}
else{
result = result + arr2.get(i);
}
Upvotes: 0
Views: 96
Reputation: 54781
You don't have to String.valueOf(num)
, str.split("")
or Integer.parseInt(arr1[i])
if you only use strings for the output and work decimal digit-by-digit using integers:
public static void dash(int someNumber) {
int lastDigit = 1;
StringBuilder sb = new StringBuilder();
while (someNumber > 0)
{
int currentDigit = someNumber % 10;
someNumber /= 10;
if (lastDigit % 2==0 && currentDigit % 2==0)
sb.append('-');
sb.append(currentDigit);
lastDigit = currentDigit;
}
String result = sb.reverse().toString(); //reverse because we processed the digits in reverse order
System.out.println(result);
}
Upvotes: 0
Reputation: 41188
Either change it to:
for(int i = 0; i < arr2.size()-1; i++) {
Or don't check i+1
if i ==arr2.size()
Upvotes: 4