Java - 如何通过main方法在另一个类中存储变量?

时间:2014-04-19 18:54:29

标签: java class object

我应该根据main方法中的用户输入将对象的变量存储到不同的类。我对#34; gerbil.id"的静态参考错误保持静态。和" gerbil.name&#34 ;;我甚至不知道它是否会保存到沙鼠类对象中的变量。有任何想法吗?这就是我到目前为止所拥有的:

编辑:现在,当我发布修复程序时,我得到一个nullpointerexceptor;这是更新的代码。例外指向gerbilArray [i] .id = keyboard.next()行。我不确定是什么原因造成的。我已将id列为字符串,并在运行时输入字符串(一个字)。

在我的信息类中:

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("How many gerbils in the lab?");
    int numberOfGerbils = keyboard.nextInt();
    Gerbil[] gerbilArray = new Gerbil[numberOfGerbils];

    for(int i = 0; i < numberOfGerbils; i++){

        System.out.print("Lab ID:");
        gerbilArray[i].id = keyboard.next();

}

gerbil 类内部:

import java.util.Scanner;
public class Gerbil {

public String id;


public Gerbil(String name) {
    this.id = "";
  }
}

3 个答案:

答案 0 :(得分:0)

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("How many gerbils in the lab?");
    int numberOfGerbils = keyboard.nextInt();
    Gerbil[] GerbilArray = new Gerbil[numberOfGerbils]; // initialization of array

    for(int i = 0; i < numberOfGerbils; i++){
        GerbilArray[i] = new Gerbil();
        System.out.print("Lab ID:");
        // String Gerbil.id = keyboard.next(); should be replaced by
        GerbilArray[i].id=keyboard.next(); // because you should call non static members using objects of a class. Here object is an array element which requires an array index.

        System.out.print("Gerbil Nickname:");
        //String name = keyboard.next(); replace by
        GerbilArray[i].name=keyboard.next();
        // as stated earlier. and you don't need to write String again because you have already declared it in the class declaration. If you try to do this way, you are creating a new String object only. This name has already been assigned to array, so it will result in an error.
    }
}

在Gerbil类中,构造函数应该更正为

public Gerbil(String name, String id) {
    this.name = name;
    this.id = id;
}

因为本地成员隐藏了类成员。这里构造函数的nameid将隐藏类的名称和id。以上陈述什么都不做。它只是一项自己的任务。 this关键字用于指向调用对象。

由于您提供的是参数化构造函数,但是您使用默认构造函数创建对象,因此您还需要明确地创建默认构造函数。

Gerbil(){}

答案 1 :(得分:0)

应该是

GerbilArray[i].id = keyboard.next();

而不是

Gerbil.id = keyboard.next();

如果你遵循用小写字母开始变量名的约定,那将有助于避免这种混淆。那么它将是:

gerbilArray[i].id = keyboard.next();

答案 2 :(得分:0)

您收到NullPointerException,因为在为阵列分配空间时出现问题。例如: numberofGerbils = 5然后 gerbilArray [0],gerbilArray [1],gerbilArray [2],gerbilArray [3],gerbilArray [4]创建

但是当你试图访问gerbilArray [5]时,它显示的是NullPointerException。 您使用了 &#34; i&lt; = numberofGerbils&#34; 不应该是&#34;&lt; =&#34; 。它应该只是&#34;&lt;&#34; 。这将解决问题。当您使用&#34; =&#34;时,调用数组索引5,实际上不存在!!!