如何按顺序命名新实例? [英] How do i name new instances in order?
问题描述
你好,
我是OOP的新手。我不得不从C#创建结构,但在Java中它不存在所以我创建了类。这个班叫做人。并且在类字符串和浮点类型中有关于人(小孩)的一些信息。在我的程序中,有时我需要生成新人。我猜这叫做创建新实例,对不起,如果我错了。因为我需要以后为特定人使用信息。所以我想我可以将他们命名为person01,person02或者他们的名字。但我不能这样做。有办法吗?或者有解决方法吗?也许有一种简单的方法可以做到我不知道。
BTW
Hello,
I am new to OOP. I had to create "structs" from C# but in Java it doesn't exist so i created class. This class is called person. And there are some info about person(child) in class string, and float types. In my program sometimes i need to generate new person. I guess that's called creating new instance, sorry if i am wrong. Because I need to use infos for spesific person later. So i thought i could name them person01,person02 or by their names. But i can't do it. Is there a way to do it? Or is there any solution way for this? Maybe there is easy different way to do it that i do not know.
BTW
public class child {
public static String name;
public static float foodConsumed;
public static float sleepConsumed;
public static float gameConsumed;
public static float hygieneConsumed;
public static void add(){
Random rnd = new Random();
child.name="child"+num;
child.foodConsumed= (float) ((rnd.nextInt(150)+50)*0.01);
child.gameConsumed= (float) ((rnd.nextInt(150)+50)*0.01);
child.sleepConsumed= (float) ((rnd.nextInt(75)+25)*0.01);
child.hygieneConsumed= (float) ((rnd.nextInt(50)+20)*0.01);
Main.num++;
Main.childQnt++;
}
}
这个孩子我必须稍后生成..
我尝试了什么:
我试图使用变量,如child01,child02:
子变量=新子();
但这不太有效。
This childs i have to generate later..
What I have tried:
I tried to use variable which changes like child01,child02:
child variable = new child();
But this didn't quite work.
推荐答案
否且它将永远不会起作用,因为您已将所有属性设置为静态,因此它们适用于子
的每个实例。从所有这些属性中删除static关键字,然后您可以创建任意数量的对象,例如:
No and it will never work because you have made all the properties static, so they apply to every instance ofchild
. Remove the static keyword from all those properties, and then you can create any number of objects like:
child Robert = new child();
Robert.name = "Robert";
// ...
child Mary = new child();
Mary.name = "Mary";
// etc
请参阅课程:类和对象 - 学习Java语言) [ ^ ]。
这篇关于如何按顺序命名新实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!