gpt4 book ai didi

java - 访问不同类中的数组列表

转载 作者:行者123 更新时间:2023-12-01 09:18:11 24 4
gpt4 key购买 nike

由于这是对我的第一个问题的再次攻击,我将首先重申我是一个 java 新手。这周我还试图完成大学水平的 Java 作业。为了说明这一点,让我说我几乎不知道自己在做什么。本周的作业得到澄清后;就是这样:

You need to write an actual ClassClient for this project that:

  1. declared and initializes your data array
  2. creates a SortingClass object,
  3. prints the array of data (unsorted)
  4. sends the array into the SortingClass's constructor (which sorts the contents of the array)
  5. prints the same array of data (now sorted)

到目前为止,我正在一步一步地完成它。目前,NetBeans 给我的唯一错误是,在我的第二个类中,使用 array1 的所有地方都带有下划线,我认为这意味着它们没有链接到放置数组列表的第一个类。我的第一个问题是,我显然没有正确链接;我缺少什么?我也在使用选择排序方法。

我的第一个类称为 ClientClass

public class ClientClass {

public static void main( double [] array ) {

double array1[] =
{53.5, 60.3, 96.2, 53.3, 56.4, 52.7, 76.4, 77.5, 71.0, 78.2,
65.2, 59.3, 80.5, 92.1, 85.7, 78.7, 66.2, 88.8, 50.2, 73.4};

//Create a SortingClass variable with data gievn in the array
SortingClass g = new SortingClass();

// Print array unsorted
for (double number : array1)
{
System.out.println("Number = " + number);
}

String outPutString = g.toString();
System.out.println(outPutString);
}

}

我已经写了第二堂课

public class SortingClass {

// Selection Sort
public static void ClientClass (double [] array )
{
double temp;
int max;

// Selection Sort Method
for (int i = 0; i < array1.length - 1; i ++)
{
max = indexOfLargestElement ( array1, array1.length - i );

temp = array1[max];
array1[max] = array1[array1.length - i - 1];
array1[array1.length - i - 1] = temp;
}
}

public static int indexOfLargestElement ( double[] array1, int size)
{
int index = 0;
for ( int i = 1; i < size; i++ )
{
if ( array1[i] > array1[index] )
index = i;
}
return index;
}
}

最佳答案

你的第一个问题是这个

sends the array into the SortingClass's constructor (which sorts the contents of the array)

翻译为:你不能到处使用static!

你需要类似的东西

public class SortingClass {
private final double data[];
public SortingClass(double data[]) {
this.data = data;
}
public void sort() {
... would sort on this.data

含义:您创建该类的一个实例,并将对该数组的引用传递到该类中。

作为初学者,您可能想要学习类似 this 的内容.

关于java - 访问不同类中的数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40367864/

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