私の現在の宿題では、ユーザーが値をその場所に挿入するときに、ジェネリック クラスを介して配列を並べ替えようとしています。サイズが完全にロードされたものとして読み取られると、配列クラスは、教授のメモに従って、適切な場所に値を保持しながら配列のサイズを増やす拡張メソッドを呼び出します。なんらかの理由で、location[0] を除くすべての値が配置されていないか、配列から消去されているようです。問題は展開方法に起因していると思いますが、これを修正する方法がわかりません。
たとえば、初期サイズは現在 5 に設定されていますが、展開メソッドが呼び出されると 3 ずつ増加します。ユーザーは値 1、2、3、4、5 を完全に入力できます。ただし、1、6、null、null、null、null の配列を出力する新しい値 6 をユーザーが入力すると、展開が呼び出されます。それ以上の場合、「スレッド "main" java.lang.NullPointerException で例外が発生しました」というエラーが発生します。
ここに私の並べ替えられた配列クラスがあります:
public class SortedArray {
private int size;
private int increment;
private int top;
Comparable[] a;
public SortedArray(int initialSize, int incrementAmount)
{
top = -1;
size = initialSize;
increment = incrementAmount;
a = new Comparable [size];
}
public int appropriatePosition(Comparable value)
{
int hold = top;
if(hold == -1)
{
hold = 0;
}
else
{
for(int i = 0; i <= top; i++)
{
if(value.compareTo(a[i]) > 0)
{
hold = i + 1;
}
}
}
return hold;
}
public Comparable smallest()
{
return a[0];
}
public Comparable largest()
{
return a[top];
}
public void insert(Comparable value)// the method that my driver calls for.
{
int ap = appropriatePosition(value);
//Expansion if full
if(full() == true)
{
expansion();
}
//Shifting numbers to top
for(int i = top; i >= ap ; i--)
{
{
a[i + 1] = a[i];
}
}
a[ap] = value;
top++;
}
public boolean full()
{
if(top == a.length -1)
{
return true;
}
else
{
return false;
}
}
public void expansion()//here's where the expansion begins
{
int newSize = a.length + increment;
Comparable[] tempArray = new Comparable[newSize];
for(int i= 0; i < a.length; i++)
{
tempArray[i]= a[i];
a = tempArray;
}
}
これは、SortedArray クラスで挿入メソッドを呼び出すドライバー クラスです。
public class IntDriver {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//Creating variables
int data;
boolean check = false;
int choice;
int size = 5;
int increment = 3;
SortedArray b = new SortedArray(size, increment);
//Creating Menu
System.out.println("Please choose through options 1-6.");
System.out.println("1. Insert\n2. Delete\n3. Clear\n4. Smallest\n5. Largest\n6. Exit\n7.Redisplay Menu");
while(check == false)
{
choice = keyboard.nextInt();
switch(choice)
{
case 1:
System.out.println("Type the int data to store in array location.");
data = keyboard.nextInt();
Integer insertObj = new Integer(data);
b.insert(insertObj);
System.out.println("The value " + data + " is inserted");
b.print();
break;