gpt4 book ai didi

Java 数组 - NullPointerException

转载 作者:行者123 更新时间:2023-12-03 23:11:36 25 4
gpt4 key购买 nike

<分区>

这是代码(包括两个类):

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)

它生成数组但不对其进行排序。如果有任何帮助,我将不胜感激。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com