这是代码(包括两个类):
import java.util.Scanner;
import java.util.Random;
public class SortedArray
{
public int [] myNums;
public int sizeOfArray;
private int userInput;
public Sort sortedArray;
public Scanner input = new Scanner(System.in);
public void sortedArray()
{
System.out.println("Enter the number of values to put in the array:");
int userInput = input.nextInt();
myNums = new int [userInput];
sizeOfArray = userInput;
for(int i=0;i<userInput;i++)
{
Random randomNum = new Random();
myNums[i] = randomNum.nextInt(100)+1;
}
for(int i=0;i<userInput;i++)
{
System.out.println(myNums[i]);
}
sortedArray = new Sort(myNums, sizeOfArray);
sortedArray.publicdisplay();
}
}
*******************************************************************************
public class Sort
{
public int[] array;
public int sizeOfArray;
public Sort(int[] oldArray, int sizeOfOldArray)
{
sizeOfArray = sizeOfOldArray;
for( int i = 0; i < sizeOfArray; i++) {
array[i] = oldArray[i];
}
sort();
}
public void publicdisplay()
{
for ( int i = 0; i < sizeOfArray; i++){
System.out.println(array[i]);
}
}
private void sort()
{
for (int i = 0; i < sizeOfArray; i++)
{
for (int j = 0; j < sizeOfArray; i++)
{
if (array[j] < array[i])
{
swap(i,j);
}
}
}
}
private void swap(int x, int y)
{
int temp = 100;
temp = array[x];
array[x] = array[y];
array[y] = temp;
}
}
程序编译正确,但是当我运行程序并输入要放入数组的值的数量时,出现以下错误:
java.lang.NullPointerException
at Sort.<init>(Sort.java:17)
at SortedArray.sortedArray(SortedArray.java:32)
它生成数组但不对它进行排序。我会很感激任何帮助,谢谢。