java - 使用用户输入和 for 循环的数组获取 NullPointerException

标签 java nullpointerexception

为什么我会收到此 NulPointerException:

Please Give the length of the Array: 
5
Please give the entries for the array for 0th index
2
Exception in thread "main" java.lang.NullPointerException
    at Array.main(Array.java:18)

In this code?

public class Array{

public static void main(String[] args) 
{
    Scanner scan = new Scanner(System.in);
    System.out.println("Please Give the length of the Array: ");
    int num= scan.nextInt();
    int arr[] = null;
    int i;
    for (i=0; i<num;i++)
    {
        if(i<num-1)
        {
            System.out.println("Please give the entries for the array for " +i+"th index");
            arr[i]=scan.nextInt();

        }
        else
        {   
            System.out.println("Please give the entries for the array for last index");
            arr[i]=scan.nextInt();

        }
    }
    scan.close();   
}
}

最佳答案

您需要初始化数组:

int arr[] = new int[num];

否则你不能在里面放任何东西。

关于java - 使用用户输入和 for 循环的数组获取 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57698483/

相关文章:

java - 无法从文件夹导入图像的随机路径? ( java )

java - 第一次加载 jsp 页面时 Spring url 无法正确解析,第一次点击后可以正常工作

javascript - Angular js中的request.getAttributes()

java - 插件 org.apache.maven.plugins :maven-resources-plugin:2. 6 或其依赖项之一无法解析

java - 可以从初始化 block 调用实例方法吗?

java - 在android中获取图片文件夹的文件夹大小时出错

android - 更改 ListView 项的文本颜色时出现 NullPointerException

java - 如何为 r.js 提供伪文件系统?

java - Android 工具栏问题

java - a.b=c;什么时候会抛出NullPointerException?其中 a、b 和 c 都是对象