我正在尝试使用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);
}
}
答案 0 :(得分:0)
您没有初始化变量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;
}
答案 1 :(得分:0)
我建议将反向数组初始化为与数字数组长度相同的数组。
int[] reverse = new int[number.length];
答案 2 :(得分:0)
您需要进行一些更改:
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]);
希望这会有所帮助。