Java:如何创建10只猫?当 Cat ("cat" + i) = "cat name" 时不像其他语言那样工作
使用循环,我可以创建
My cat is: Cat1
...
My cat is: Cat1
但是,当我尝试使用时,
Cat ("cat"+i) = new Cat("Cat" + i);
我犯了错误......
那么,纠正我的代码以生成
cat1 ... cat10 cat instances?
public class TestCat{
public static void main(String [] args){
for (int i=1; i<10; i++){
//Cat ("cat"+i) = new Cat("Cat 1");
Cat cat1 = new Cat("Cat 1");
System.out.println("My cat is: " + cat1 );
}
}
}
class Cat{
static String catName;
public Cat(String catName){
this.catName=catName;
}
public String toString(){
return catName;
}
}
对不起......我应该说的
最简单方法是什么如何创建十个10 Cat实例.....cat1,...cat2.....因为在其他语言中,我可以使用“cat”||i = ...,来创建不同的变量,我想知道如何我可以在 Java 中做类似的事情......
换句话说,我想通过考虑循环信息来命名我将要创建的实例。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
如果您不知道自己会养多少只猫,请使用收藏。
注意:这段代码产生了不正确的结果,让我感到困惑,直到我仔细查看 Cat 类。
罪魁祸首就是:
删除
static
,你就成功了。Use a collection if you don't know how many cats you'll have.
Note: This code produces incorrect results and had me stumped until I looked closer at the Cat class.
Here was the culprit:
Remove the
static
and you are golden.这看起来像是一个学术问题,所以我会这样处理它。你需要在某个地方存放十只猫。您可以做到这一点的一个地方是在数组中..
This looks like an academic problem, so I'll approach it as such. You need to store ten cats somewhere. One place you can do that is in an array..
上面有很多答案,所以我只补充一点,你不能在 Java 中动态更改变量名称,所以下面的粗体部分是一个诺诺:
Cat ("cat"+i) = new Cat( “猫 1”);
Lots of answers above so I'll just add that you can't dynamically change variable names in Java, so the bolded part below is a nono:
Cat ("cat"+i) = new Cat("Cat 1");
您正在对猫号进行硬编码:
您应该将其更改为:
对吗?
You're hardcoding the cat number:
You should change that to:
Right?
你需要一个数组。
这将创建并存储 10 只猫。
那么打印也是类似的:
You need an array.
This creates and stores the 10 cats.
Then printing is similar:
你可以这样做:
You can do:
Java 不支持动态命名变量,因此您无法使用以下命令创建“cat1”到“cat10”:
(顺便说一句,您来自哪种语言?)
Java 方法是创建一个数组(正如其他人所建议的那样)。如果您不知道需要多少个实例,您可以动态调整数组的大小:
您也可以使用列表而不是数组。
Java does not support dynamically named variables, so you can't create "cat1" through "cat10" with:
(BTW, what language are you coming from?)
The Java way would be to create an array (as others have suggested). If you don't know how many instances you will need, you can dynamically size the array:
You could also use a List instead of an array.
您可以创建n只猫:
代码:
You can create n number of Cats :
Code: