java - 将数组与对象一起使用? java

标签 java arrays class object

我是 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();

关于java - 将数组与对象一起使用? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33238405/

相关文章:

java - Google Protobuf 反序列化重复对象上 get 操作的时间复杂度

php - mysql fetch array 如果没有结果显示消息

c++ - 在 const 方法中使用引用

java - 如何在不创建新对象的情况下从另一个类访问变量

java - 将文件保存到Java中的特定目录?

java - 根据数字程序设置GridView的ImageVIew

java - Java 的 AVL 树实现

Java 从不同的类中普遍加载整数

javascript - JS或jQuery方法将json排列成多维数组

python - 如何在python中调用另一个类的函数