我是Java新手,想知道下面的代码有什么问题。我试图将多个对象创建为数组(如果可能)?该代码将运行并询问名称,但是在此之后刚刚结束,我不确定为什么。任何帮助将是巨大的,在此先感谢。



import java.util.Scanner;


public class test {

    public static void main(String[] args) {


    	ABug[] BugObj = new ABug[3]; //Creating object BugObj of class ABug



    	for (int i=1; i<4; i++){
    	Scanner reader = new Scanner(System.in);
        System.out.println("Please enter the name of the bug:");
		BugObj[i].name = reader.next();
    	System.out.println("Please enter the species of the bug:");
    	BugObj[i].species = reader.next();


    	System.out.println("Name: " + BugObj[i].name);           //Printing bug information out
    	System.out.println("Species: " + BugObj[i].species);

    	}
    }
}

class ABug {
	int horpos, vertpos, energy, id;
	char symbol;
	String species, name;

}

最佳答案

您有两个问题:


您需要具有要使用的对象的实例。
管理for循环的方式。


您可以将源代码修改为此:

Scanner reader = new Scanner(System.in); // Take out this from inside for loop

for (int i = 0; i < BugObj.length; i++) { // Notice we use BugObj.length instead of a number and start index at 0.
  System.out.println("Please enter the name of the bug:");
  BugObj[i] = new ABug(); // You need to initialize the instance before use it
  BugObj[i].name = reader.next();

09-13 04:19