gpt4 book ai didi

java - 在java中声明一个对象数组(包括代码)?

转载 作者:太空宇宙 更新时间:2023-11-04 14:57:37 25 4
gpt4 key购买 nike

public class Pig {
private int pigss;
private Pig[] pigs;

public Pig[] pigNumber (int pigss)
{
pigs = new Pig [pigss];
return pigs;
}

包含main方法的代码:

public class animals{

public static void main(String[] args){

Pig cool = new Pig();
Scanner keyboard = new Scanner (System.in);

System.out.println("How many pigs are there?");

int pigss = Integer.parseInt( keyboard.nextLine() );
cool.pigNumber(pigss);
//This is where I have trouble. I want to use the array pigs here in the main method, this is what i tried:

Pig[] pigs = cool.pigNumber(pigss);

然后我尝试使用 for 循环并将值(字符串)分配给数组索引(pigs[])。但给我的错误是:无法从 String 转换为 Pig。任何提示表示赞赏。谢谢。

     for(int j = 0; j < pigs.length; j++)
{
System.out.println("What is the pig " + (j+1) + "'s name");
pigs[j] = keyboard.nextLine();

}

最佳答案

您的 pig 将需要一个属性来包含您尝试传递的字符串值:

public class Pig {

private String name;

public void setName(String n) {
name = n;
}

public String getName() {
return name;
}

然后当你想将此字符串值分配给你的 pig 时:

int indexOfPig = 0; // Or whatever it is supposed to be
pigs[indexOfPig].setName("I am a string");

在java中只能使用int作为数组的索引

关于java - 在java中声明一个对象数组(包括代码)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23002575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com