简体   繁体   English

如何在另一个类和方法中使用数组中的数据?

[英]How to use Data from an array in another class & method?

I've got a class named "User" which has a method that makes the User type his name. 我有一个名为“ User”的类,该类具有使User类型成为他的名字的方法。 This name is saved in an array that is empty at first. 此名称保存在一个最初为空的数组中。

Question is, how can I use this "stored" name in another class (I want to show the name in this other class) 问题是,如何在另一个班级中使用此“存储的”名称(我想在另一个班级中显示该名称)

Here's what I've got (Sorry for the spanish lol) 这就是我所得到的(对不起西班牙大声笑)

public class Usuario {
    private Scanner entrada = new Scanner(System.in);
    private String Usuario[] = new String[20];
    private int Posicion = 0;
    private int punteo;

public void Datos() {
    System.out.println("Ingresa tu nombre");

    if(Usuario[Posicion] == null) {
        this.Usuario[0] = entrada.nextLine();
        Posicion++;
    }

}
public String Usuario() {
    return Usuario[Posicion-1];
}     

And I want to use the name ( Usuario[Posicion-1] ) for example in a class like this: 我想在这样的类中使用名称( Usuario[Posicion-1] ):

public class Score extends Usuario {
    Usuario usr = new Usuario();
    String[] Name = new String[20];

    public void Score () {
        Name[0]=usr.Usuario();

        System.out.println("------------Scores ------------------");
        System.out.println("    Name          "+ "            Score");
        for(int i=0;i<11;i++) {
            System.out.println(i+".- " + " "+Name[0] +"                        200 ");
        }
    }
}

But Everytime I try to retrieve this data in this class I get a "null" value or an "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1" error, which makes me believe that I can't use the information from the array in another class :( 但是每次我尝试在此类中检索此数据时,都会得到“空”值或“线程“主”中的异常” java.lang.ArrayIndexOutOfBoundsException:-1”错误,这使我相信我无法使用该信息从另一个类的数组中:(

I'd appreciate any help. 我将不胜感激。 (also Sorry for the not-so-good english). (也很抱歉英语不太好)。

Each new version of a class or an object is not going to have the same values. 类或对象的每个新版本都不会具有相同的值。

you will have to get the name from the object User.name then set it in your other object secondObject.name = User.name 您将必须从对象User.name获取名称,然后在另一个对象中设置它。secondObject.name = User.name

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

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