-2
public class Persona {

    private String nombre, DNI;
    private char sexo;
    private int edad, altura;
    private float peso;

    Persona(){
        nombre = "";
        sexo = 'M';
        edad = 0;
        altura = 0;
        peso = 0; 
    }

    String generaDNI(){
        String DNI = "";
        int x = (int)(Math.random() * 100000000 + 1);
        DNI += Integer.toString(x);
        return DNI;
    }

}

So this is my code. What I want to do is, whenever I call the constructor, i want the attribute "DNI" to call the method "generaDNI", so the value of "DNI" is given by the method. How can I do it?

dimo414
  • 47,227
  • 18
  • 148
  • 244
A. Gisbert
  • 153
  • 2
  • 11

2 Answers2

1

Are you looking to do DNI = generaDNI(); in the constructor? You can just add that line, e.g.:

Persona(){
    nombre = "";
    DNI = generaDNI();
    sexo = 'M';
    // you don't need to set edad, altura, or peso - they default to 0
}

Consider making generaDNI() static, final, and/or private, as well. Calling instance methods from inside the constructor is allowed, but can introduce surprising bugs if misused.

Community
  • 1
  • 1
dimo414
  • 47,227
  • 18
  • 148
  • 244
0

You can call it within the constructor and assign the value to DNI attribute of the class:

Persona() {
    nombre = "";
    DNI = generaDNI();
    sexo = 'M';
    edad = 0;
    altura = 0;
    peso = 0;
}
manfcas
  • 1,933
  • 7
  • 28
  • 47
  • 2
    Hi! It looks like you are new to StackOverflow. I can remember that when I started out, it was tough to get upvotes and become a part of the community. So I'd just like to give you a few tips on posting on SO! :) You should add formatting to your code. That'll make your solution a lot easier to understand. Also make sure that your post does not contain typos (like 'do class'). Also, you should include a more explicit description of how your answer solves a given question. I upvoted your answer since, despite the few small mistakes, it is good. See @dimo414's answer for a positive example. – FMaz Dec 16 '16 at 20:42