我试图将一个数字插入到无序数组中,但它有一些逻辑错误。使用的代码是,
int NoOfItems = 5 ;
int MyArray[] = {1,6,3,9,5};
Scanner input = new Scanner(System.in);
System.out.println("Enter a Number:");
int m_Number = input.nextInt();
if (NoOfItems < MyArray.length) {
MyArray[NoOfItems] = m_Number;
NoOfItems = NoOfItems + 1;
}
System.out.println(Arrays.toString(MyArray));
请帮我解决这个问题。
最佳答案
您的 MyArray 数组的长度为 5,因此它可以保存索引 0-4 中的对象。您试图在索引 5 中插入一个对象,这将给您带来 ArrayIndexOutOfBounds 异常。请注意,Java 中的数组具有不可变的大小。
您需要创建一个大小为 6 的新数组并将旧数组的内容复制到其中,然后添加第 5 个索引。否则,您可以使用ArrayList
关于java - 将项目插入无序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37084928/