我在C中有以下代码,而且我对Java知之甚少。
我想知道是否有任何方法可以在Java中创建下面代码中显示的结构。我想我们可以在Java中使用class
来完成它,但我在Java Classes中遇到的问题是我无法声明人[10],即这样一个结构的数组。
struct people{
float height;
float weight;
int age;
}people[10];
int main() // this part of code is just to show how I can access all those elements of struct
{
int i;
for(i=0;i<10;i++)
{
people[i].height = rand()%7;
people[i].weight = rand()%80;
people[i].age = rand()%100;
}
for(i=0;i<10;i++)
{
printf(" %f %f %d\n",people[i].height,people[i].weight,people[i].age);
}
return 0;
}
答案 0 :(得分:9)
在 C ++ 中,您可以静态分配对象..
struct People
{
// struct members are public by default
float height;
float weight;
int age;
}
people[10]; // array of 10 objects
int main ()
{
// fill some data
people[0].age = 15;
people[0].height = 1.60;
people[0].weight = 65;
return 0;
}
但是在 Java 中,你必须动态分配对象,并且创建数组不会分配对象,它只会分配一个引用数组。
package Example;
private class People
{
// define members as public
public float height;
public float weight;
public int age;
}
class Main
{
public static main (String [] args)
{
// array of 10 references
People [] p = new People [10];
// allocate an object to be referenced by each reference in the array
for (int i=0; i<10; i++)
{
p[i] = new People();
}
// fill some data
people[0].age = 15;
people[0].height = 1.60;
people[0].weight = 65;
}
}
答案 1 :(得分:2)
我将如何做到这一点:
public class Person {
public float height;
public float weight;
public int age;
private static Person[] people = new Person[10];
public static void main(String[] args) {
java.util.Random r = new java.util.Random();
for (int i = 0; i < 10; ++i) {
people[i] = new Person();
people[i].height = r.nextInt(7);
people[i].weight = r.nextInt(80);
people[i].age = r.nextInt(100);
}
for(int i = 0; i < 10; ++i) {
System.out.printf(" %f %f %d\n",
people[i].height, people[i].weight, people[i].age);
}
}
}
答案 2 :(得分:0)
public class Person{
private float height;
private float weight;
private int age;
public Person(float height, float weight, int age)
{
this.height = height;
this.weight = weight;
this.age = age;
}
public float getHeight() { return height;}
...
...
public static void main(String[] args)
{
int N=10;
Person[] people = new Person[N];
for(int i=0; i<N; i++)
people[i] = new Person( ... , ... , ...)
}
}
答案 3 :(得分:0)
你应该使用课程。为了创造人,你必须创建该类的对象。
people [] p = new people[10];
for(people person : p )
{
//each object is defined.
p = new People(h,w,age);
}
class People{
People(int h, int w, int a)
{
height=h; weight=w; age=a;
}
float height;
float weight;
int age;
}