Problem with the methods and constructor?

3

I have a small code in which the purpose is to verify the user's name and see if it exists in an array and the age verify if it is of legal age. If it is, you are authorized to enter the system.

The code is not finished yet but my doubt is that I have a String method that receives a parameter called name that is in another class and is inherited through the main class called MyName I have two Defined fields private (should define them or public because the method of the other class will use them), well then in the main class I define a constructor by which define (start) by default the values there is my other problem I have two objects an object type String and another type ID the beria define asi like as?

Here is the code to see what I have:

Main class

/*Proposito del programa:
 el proposito del programa es verificar el name del usuario y ver si exsite en un array y la edad 
 verificar si es mayor de edad si lo es es autorizado a entrar al sistema.
*/

public Class MyClass extends Methods {
    public static void main(String[]args) {
    //Campos 
        private String name;
        private int edad;

        //Creo los objetos name(nombre) y edad(la edad del usuario)
        String user = new String();
        id edad = new id();
        /* Mi problema es aqui en los objetos deberia crearlos asi o como ?*/
        //Constructor 
        public MyClass {
            user.Getname = "Gilberto quintero";
        }
        Scanner entrada = new Scanner(System.in);   
    }    
}

The other class

public Class Methods {
    public String Getname(String name) {
        System.out.println("Hola bienvenido a"+name);
    }    
}
    
asked by simon 08.01.2017 в 21:32
source

3 answers

1

Although it has been difficult for me to understand what you are asking for, I think that this is the most correct according to your needs. I have commented on the code in such a way that I hope you understand the operation of the program without problems.

Class Methods:

public class Methods{

  /* Método que comprueba si nombre esta en el array
  *  Si esta: Saluda
  *  Si no esta: avisa de que no es valido el nombre
  *  El array si le pasa como parametro (Asi te vale para otros casos)
  *  El nombre se le pasa como parametro
  *  Si el método saluda, ¿para que va a devolver nada? => el metodo es void
  */
  public static void getName(String nombre, String[] array){
      boolean esta = false;
      // Lo busco en el array desde la primera posicion a la ultima, si lo encuentro paro
      for(int i = 0 ; i < array.length && !esta ; i++) // Va hasta el final buscando nombre, si lo encuentra para
          if(nombre.equals(array[i])) // Como String son OBJETOS se usa EQUALS
              esta = true;
      if(esta) // es equivalente a esta == true
          System.out.println("Bienvenido: " + nombre);
      else
          System.out.println(nombre + " no esta en la base de datos");
  }
}

MyName class that inherits from Methods the method it looks for in the array

// para poder usar el Scanner lo tenemos que tener, lo importamos
import java.util.Scanner;
public class MyName extends Methods{

  /* Metodo principal del programa: aqui empieza el programa
  *  El programa o se conecta a una base de datos de verdad o 
  *  tiene que saber que usuarios son validos y cuales no. 
  *  Creamos el array nosotros para hacer la prueba
  *  El array se puede crear dentro aunque por convenio mejor fuera
  */
  public static void main(String[] args){
      /* Para pedir cosas por teclado al usuario necesitamos Scanner */
      Scanner  teclado = new Scanner(System.in);

      // Necesitamos dos variables para guardar el nombre y la edad
      String nombre;
      int edad;

      // Se los pedimos la usuario
      System.out.print("Por favor, introduzca su nombre para entrar al sistema: ");
      nombre = teclado.nextLine(); // Pedimos texto con espacios
      System.out.print("Por favor, introduzca su edad para entrar al sistema: ");
      edad = teclado.nextInt(); // Pedimos un numero

      if(edad < 18)
          System.out.println("No permitido a menores de edad");
      else
          getName(nombre, array);
  }

  /* Aunque no lo veamos el método getName(nombre, array) esta aqui */

  /* Creamos el array, aqui o arriba da igual aunque mas intuitivo arriba */

  private static String[]  array = {"Alonso" , "Jaime" , "Rodrigo"};
}

I hope it will help you and clarify the concepts. Any questions you have question!

    
answered by 12.01.2017 / 16:55
source
2

There are some errors.

  • A constructor is a method to start a class should not be within a method as is the case you put in a main.
  • Class attributes are defined outside of a method.
  • Class is not used to define a class in Java. In java is case sensitive. Class and Class are not the same. The correct thing would be public class MyClass extends Methods {}
  • Generally by convention a method is written in lowercase. If you have compound words write something similar to getName. It is not mandatory in this way, but most Java developers write like this.
  • Generally a class will define the values and with their respective methods. In another class, the main method is defined. But it depends on your needs. It is not strict.
  • Inheritance is to extend a class. In my example I do not use, but I leave you a link that will serve you a lot.

I'll show you in more or less example so that you can see and expand to your needs

Example:

The MyClass class

public class MyClass{
    // Campos 
    private String name;
    private int edad;

    // Constructor 
    public MyClass(String name, int edad){
        // Se guardan el name y la edad en la clase en sus respectivos atributos.
        this.name = name;
        this.edad = edad;
    }  

    public String getName(String name) {
        return this.name;
    } 

    public int getEdad(int edad) {
        return this.edad;
    } 

    public String saludo(String saludo) {
        String name_tmp = saludo + " " + name;
        System.out.println(name_tmp);
        return this.name;
    } 
}

The Methods class

public class Methods {
     public static void main(String[]args) {
         // Crear un objeto MyClass
         MyClass miPrimeraClase = new MyClass("Jose", 31);

         // Saludo.
         miPrimeraClase.saludo("Hola bienvenido a");
     }
}

Obs:

  • In the MyClass class, do not add the set methods of each attribute. The idea of my example so you can expand your needs and have a code that works.
answered by 08.01.2017 в 22:23
1

I did not quite understand your code and what you put in the proposal what you could do with two simple Java classes.

User.java

public class Usuario
{
    private String nombre;
    private int edad;
    private static final int MAYORIA_EDAD = 18;

    public Usuario(String nombre, int edad)
    {
        this.nombre = nombre;
        this.edad = edad;
    }

    boolean menor()
    { return edad < MAYORIA_EDAD; }

    @Override
    public String toString()
    { return nombre + " - " + edad + " años"; }

    @Override
    public boolean equals(Object obj)
    {
        if(obj == null)
            return false;
        else if(obj instanceof Usuario == false)
            return false;
        else
        {
            Usuario usr = (Usuario) obj;
            return this.nombre.equals(usr.nombre);
        }
    }
}

Aplicacion.java

import java.util.ArrayList;

public class Aplicacion
{
    // Uso un ArrayList porque me gusta más
    private ArrayList<Usuario> usuarios;

    public Aplicacion()
    {
        usuarios = new ArrayList<>();
    }

    public void nuevoUsuario(Usuario usr)
    { usuarios.add( usr ); }

    public boolean autorizar(Usuario usr)
    {
        boolean encontrado = false;
        for (Usuario u : usuarios) 
        {
            if( u.equals(usr) )
                encontrado = true;
        }
        // Si buscar se puede hacer de forma más eficiente, pero no quiero liarme con esto

        if(encontrado)
        {
            if( usr.menor() )
                return false;
            else
                return true;
        }
        else
            return true;
    }

    public static void main(String[]args)
    {
        Aplicacion app = new Aplicacion();
        Usuario usrMayor = new Usuario("jpuriol", 20);
        Usuario usrMenor = new Usuario("peque", 10);

        System.out.print("Añadiendo nuevos usuarios");

        app.nuevoUsuario(usrMayor);
        app.nuevoUsuario(usrMenor);

        System.out.println("**hecho**");

        System.out.print("**El usuario " + usrMayor + " intenta entrar**");
        boolean autorizacion1 = app.autorizar(usrMayor);
        System.out.println("RESULTADO: " + autorizacion1);

        System.out.print("**El usuario " + usrMenor + " intenta entrar**");
        boolean autorizacion2 = app.autorizar(usrMenor);
        System.out.println("RESULTADO: " + autorizacion2);

        // Falta probar el caso de que no se encuentre
    }
}

It does not answer your question directly but I hope it helps you.

    
answered by 08.01.2017 в 22:50