简体   繁体   English

访问另一个类中的数组?

[英]Accessing an array in another class?

I am working on a program that will add randomly generated numbers to an array. 我正在开发一个将随机生成的数字添加到数组的程序。 I need to be able to track how many numbers are generated before a duplicate number is generated. 我需要能够跟踪生成重复数字之前生成了多少个数字。 I have an interface and and ArrayIntLog class. 我有一个接口和ArrayIntLog类。 the class holds an int[]. 该类拥有一个int []。

I get an error before I run my program that says "array required, ArrayIntLog found. If i understand what i have done right, the ArrayIntLog is storing input into the array log, but I'm not sure how to access that array from my TestLuck Class? I've tried using the name myLog[index] and just log[index] but but those give me errors as well. 我在运行程序之前收到一条错误消息,提示“需要数组,找到ArrayIntLog。如果我理解正确,则ArrayIntLog将输入存储到数组日志中,但是我不确定如何从我的数组访问该数组。 TestLuck Class?我试过使用名称myLog [index]而只是使用log [index],但是这些也会给我带来错误。

Here is my TestLuck class: 这是我的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");
                }
            }
        }

    }
}

Here is my ArrayIntLog class: 这是我的ArrayIntLog类:

package arrayintlog;


public class ArrayIntLog implements IntLogInterface
{
    protected String name; //name of the IntLog
    protected int[] log; //array that holds the integers
    protected int lastIndex = -1;

    //==========================Constructor=====================================
    public ArrayIntLog(String name, int maxSize)
    {
        log = new int[maxSize];
        this.name = name;
    }

    //==========================Constructor=====================================
    public ArrayIntLog(String name)
    {
        log = new int[100];
        this.name = name;
    }

    //===========================Insert=========================================
    public void insert(int element) 
    {
        lastIndex++;
        log[lastIndex] = element;
    }

    //===========================isFull=========================================
    public boolean isFull() 
    {
        if(lastIndex == (log.length - 1))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    //============================Size==========================================
    public int size() 
    {
        return lastIndex + 1;
    }

    //===========================Contains=======================================
    public boolean contains(int element) 
    {
        int location = 0;
        while (location <= lastIndex)
        {
            if (element == (log[location]))
            {
                return true;
            }
            else
            {
                location++;
            }
        }
        return false;
    }

    /*=============================Clear========================================
    public void clear() 
    {
        for (int index = 0; index <= lastIndex; index++)
        {
            log[index] = null;
        }
        lastIndex = -1;
    }*/

    //=============================getName======================================
    public String getName() 
    {
        return name;
    }

    public String toString()
    {
        String logString = "Log " + name +"/n/n";

        for (int index = 0; index <= lastIndex; index++)
        {
            logString = logString + (index+1) + ". " +
                    log[index] + "/n";
        }
        return logString;
    }
}

Here is my IntLogInterface: 这是我的IntLogInterface:

package arrayintlog;


public interface IntLogInterface 
{
    void insert(int element);
    //precondition: IntLog is not full
    //places element into the log

    boolean isFull();
    //returns true if the IntLog is full

    int size();
    //returns the number of elements in this IntLg

    boolean contains(int element);
    //return true if the IntLog contatains an element

    //void clear();
    //makes this IntLog empty

    String getName();
    //returns the name of this IntLog

    String toString();
    //returns a formatted string representing this IntLog 
}

If you need to access a non public variable of other class you better call the getter method of that variable. 如果您需要访问其他类的非公共变量,则最好调用该变量的getter方法。

Add this in your ArrayIntLog class:- 将此添加到您的ArrayIntLog类中:

public int get(int index) {
        return log[index];
    }

And change the if condition to the below in your main method:- 并在您的主要方法中将if条件更改为以下内容:

if (newLog.get(index) == (newLog.get(index2)))
                {
                    System.out.println("You had to generate " + index + "numbers get a match");
                }

I didn't compile your code, but I think the error is in the line : if (newLog[index].contains(newLog[index2])) You've defined the object of class ArrayIntLog like this: 我没有编译您的代码,但我认为该错误在一行中: if (newLog[index].contains(newLog[index2]))您已经定义了ArrayIntLog类的对象,如下所示:

ArrayIntLog newLog = new ArrayIntLog(name);

But then you're trying to access it by calling : newLog[index] its illegal in Java. 但是,然后您尝试通过调用: newLog[index]来访问它,这在Java中是非法的。 You might want to define an additional method in class ArrayIntLog + in the interface, something like this: 您可能需要在接口中的ArrayIntLog +类中定义其他方法,如下所示:

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];
  } 
}

This would give you an acess to the array. 这将使您能够访问阵列。 BTW, even in this case, it would be an error, because you can't do something like if (newLog.get(index).contains(newLog.(index2))) . 顺便说一句,即使在这种情况下,这也将是一个错误,因为您无法执行if (newLog.get(index).contains(newLog.(index2))) I assume you meant this: if (newLog.contains(newLog[index2])) or maybe : if (newLog.get(index) == newLog[index2])) , I didn't check the logic of the code. 我假设您的意思是: if (newLog.contains(newLog[index2]))或也许: if (newLog.get(index) == newLog[index2])) ,我没有检查代码的逻辑。

BTW, just an advice, java compiler produces pretty good error messages, you should even have an exact line of code where the compile fails to do its job. 顺便说一句,只是一个建议,java编译器会产生非常好的错误消息,您甚至应该在编译无法完成其工作的地方使用确切的代码行。 So it really worth to reading these compilation errors and trying to understand them. 因此,真正值得阅读这些编译错误并尝试理解它们。

Hope this helps 希望这可以帮助

To access a contents of the array 'log' from other object, the 'ArrayIntLog' class must have a public method which provide access to the aray 'log'. 要从其他对象访问数组“ log”的内容,“ ArrayIntLog”类必须具有一个公共方法,该方法提供对aray“ log”的访问。

For example: 例如:

Add following code into the 'ArrayIntLog' class, and add "int getData(int index);" 将以下代码添加到“ ArrayIntLog”类中,并添加“ int getData(int index);” into the interface IntLogInterface. 进入接口IntLogInterface。

public getData(int index)
{
    return log(index);
}

Then you can get data from the array of newLog object which is an instance of 'ArrayIntLog' class as follows. 然后,您可以从newLog对象的数组获取数据,该对象是'ArrayIntLog'类的实例,如下所示。 This example accesses third element of the array. 本示例访问数组的第三个元素。

  thirdDataInArray = newlog.getData(3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM