Intellij Idea 我可以打印整个数组而不会得到'无法读取字段'值',因为'另一个'是空'错误吗?

j8yoct9x  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(61)

好吧,我试图创建一个程序,这是要打印数是递减数使用rays.sort(array, Collections.reverseOrder());方法。
它给了我一个错误。因为数组的某些值是NULL。error msg -Exception in thread "main" java.lang.NullPointerException: Cannot read field "value" because "anotherInteger" is null
范例:如果我把5作为number的值,那么只有数组的前5个元素有值,所以它显示了一个错误。
这是代码

int number = sc.nextInt();
            Integer array[]= new Integer[10];
            for(int j=0;j<number;j++){  // here number is the number of inputs,
                    array[j]= sc.nextInt();
            }
            Arrays.sort(array, Collections.reverseOrder()); // to sort our array
            System.out.println(Arrays.toString(array));

字符串
现在,有没有什么方法可以打印整个数组而不会得到错误消息?

6rqinv9w

6rqinv9w1#

解决方案:

int numbersAmount = sc.nextInt();
Integer[] array = new Integer[numbersAmount];
for(int j = 0; j < array.length; j++){
    array[j] = sc.nextInt();
}
Arrays.sort(array, Collections.reverseOrder());
System.out.println(Arrays.toString(array));

字符串

另外:

想一想:

  • 如果您在没有任何输入的情况下按ENTER键会怎样?
  • 如果输入的是字母,按ENTER键会怎样?

相关问题