Java 访问另一个类中的数组?
我正在开发一个程序,将随机生成的数字添加到数组中。我需要能够跟踪有多少数字生成之前,重复的数字生成。我有一个接口和ArrayIntLog类。该类包含一个int[] 我在运行程序之前遇到一个错误,上面写着“array required,ArrayIntLog found”。如果我理解正确,ArrayIntLog将输入存储到数组日志中,但我不确定如何从我的TestLuck类访问该数组?我尝试使用名称myLog[index]和log[index],但这些都会给我带来错误 这是我的TestLuck课程:Java 访问另一个类中的数组?,java,arrays,Java,Arrays,我正在开发一个程序,将随机生成的数字添加到数组中。我需要能够跟踪有多少数字生成之前,重复的数字生成。我有一个接口和ArrayIntLog类。该类包含一个int[] 我在运行程序之前遇到一个错误,上面写着“array required,ArrayIntLog found”。如果我理解正确,ArrayIntLog将输入存储到数组日志中,但我不确定如何从我的TestLuck类访问该数组?我尝试使用名称myLog[index]和log[index],但这些都会给我带来错误 这是我的TestLuck课程:
package arrayintlog;
import java.util.Random;
public class TestLuck
{
public static void main(String[] args)
{
int cycles = 0;
String name = "myLog";
int min = 1;
int max = 10000;
int duplicateCheck;
Random rand = new Random();
int random = rand.nextInt(max - min + 1) + min;
ArrayIntLog newLog = new ArrayIntLog(name);
for (int index = 0; index < newLog.size(); index++)
{
newLog.insert(random);
for(int index2 = 0; index2 < newLog.size(); index2++)
{
if (newLog[index].contains(newLog[index2]))
{
System.out.println("You had to generate " + index + "numbers get a match");
}
}
}
}
}
如果需要访问其他类的非公共变量,最好调用该变量的getter方法 将其添加到ArrayIntLog类中:-
public int get(int index) {
return log[index];
}
并将主方法中的if条件更改为以下条件:-
if (newLog.get(index) == (newLog.get(index2)))
{
System.out.println("You had to generate " + index + "numbers get a match");
}
我没有编译您的代码,但我认为错误在以下行:
if(newLog[index].contains(newLog[index2])
您定义了类ArrayIntLog的对象,如下所示:
ArrayIntLog newLog = new ArrayIntLog(name);
public class ArrayIntLog {
///...... the rest of the code:
public int get(int index) {
// you might want to check bound here as well, its your decision...
return log[index];
}
}
但是,您试图通过调用来访问它:newLog[index]
在Java中是非法的。
您可能希望在接口中的类ArrayIntLog+中定义一个附加方法,如下所示:
ArrayIntLog newLog = new ArrayIntLog(name);
public class ArrayIntLog {
///...... the rest of the code:
public int get(int index) {
// you might want to check bound here as well, its your decision...
return log[index];
}
}
这将为您提供对数组的访问权限。顺便说一句,即使在这种情况下,这也是一个错误,因为您无法执行类似于if(newLog.get(index.contains)(newLog.index2))
的操作。我想您的意思是:
if(newLog.contains(newLog[index2]))
或者:if(newLog.get(index)==newLog[index2])
,我没有检查代码的逻辑
顺便说一句,java编译器产生了非常好的错误消息,你甚至应该有一行编译失败的代码。所以阅读这些编译错误并试图理解它们是非常值得的
希望这有助于要从其他对象访问数组“log”的内容,“ArrayIntLog”类必须具有提供对aray“log”的访问的公共方法 例如: 将以下代码添加到“ArrayIntLog”类中,并添加“int-getData(int-index)”;“输入到接口IntLogiInterface
public getData(int index)
{
return log(index);
}
然后,您可以从newLog对象的数组中获取数据,该数组是“ArrayIntLog”类的一个实例,如下所示
thirdDataInArray = newlog.getData(3);
log[index]
总是非法的,除非log
是数组。[]
语法只适用于数组,句号,ArrayIntLog
不是数组。对,但在我的ArrayIntLog类中,构造函数中有一个数组。因此每次我都执行newLog.insert(随机)我应该将数字添加到数组中,但我不知道如何访问该数组,以便在运行时检查重复的数字。