我正在尝试使用do-while反转Integer数组中的每个数字,但是我得到NullPointerException错误。我正在尝试反转此数组中的每个元素:例如,如果这是我的数组:{12,34,56}然后结果必须是:{21,43,65}。有人可以帮我这个吗?
public class Reverse {
public int[] revCalculator(int[] number) {
int[] reverse = null;
for (int j = 0; j < number.length; j++) {
do {
reverse[j] = reverse[j] * 10 + number[j] % 10;
number[j] /= 10;
} while (number[j] > 0);
}
return reverse;
}
}
public class ShowReverse {
public static void main(String[] args) {
// instantiation
// -----------------------------------------
Reverse rev = new Reverse();
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Enter The Number Of Elements: ");
int len = in.nextInt();
int[] numbers = new int[len];
for (int i = 0; i < len; i++) {
System.out.println("Enter Number: ");
numbers[i] = in.nextInt();
}
int[] result = rev.revCalculator(numbers);
// shows the result
// -----------------------------------------
System.out.println("THE REVERSE WOULD BE: ");
System.out.print(result);
}
}
你没有初始化你的变量reverseArray
,初始化它是这样的:
更新,我看到你要做的是什么,你想要反转数组的值,而不是数组本身
public int[] revCalculator(int[] number) {
int[] reverse = new int[number.length]; //Initialize it to the same size as the passed in arary
//int[] reverse = null; //Problem
StringBuilder sb = new StringBuilder();
for (int j = 0; j < number.length; j++)
{
//You could convert the number to string then reverse it and use parseInt() int
reverse[j] = parseInt(sb.append(number[j].toString()).reverse().toString());
//Clear the StringBuilder object
sb.setLength(0);
}
return reverse;
}
我建议将反向数组初始化为与数组相同长度的数组。
int[] reverse = new int[number.length];
您必须进行一些更改:
int[] reverse = new int[number.length];
System.out.print(result);
会给你结果数组的地址。您必须显示数组的元素。
int[] result = new int[numbers.length];
result = rev.revCalculator(numbers);
// shows the result
// -----------------------------------------
System.out.println("THE REVERSE WOULD BE: ");
//System.out.print(result);
for(int i = 0 ; i<result.length; i++)
System.out.println(result[i]);
希望这可以帮助。