I am creating an application where each user has their respective profile. These profiles are stored in a ArrayList
. I have problems when creating a method to search for users registered or present in ArrayList
it and I have to do it with 2 parameters Nombre
and Apellido
.
I have the following class:
import java.util.*;
public class Profilo {
static String Nombre;
static String Apellido;
String Intereses;
boolean visible;
//contructor
public Profilo(String nombre, String apellido,String intereses,
boolean visibilidad) {
this.Nombre= nombre;
this.Apellido= apellido;
this.Intereses= intereses;
this.visible = visibilidad;
}
public String getNombre() {
return this.Nome;
}
public String getApellido() {
return this.Cognome;
}
And another class that will contain the methods to login, register and search for users:
import java.util.ArrayList;
import java.util.Scanner;
public class PerfilManager {
static ArrayList<Profilo> Users = new ArrayList();
static Scanner sc = new Scanner(System.in);
public static void Login() {
//codigo
}
public static void Registrarse() {
//codigo
}
public static void InizializaDati(){
String nombre;
String apellido;
String intereses;
boolean visibile;
System.out.println("nombre:");
nombre= sc.next();
System.out.println("apellido:");
apellido = sc.next();
System.out.println("intereses:");
intereses= sc.next();
System.out.println("visible?(true/false)");
visibile = sc.nextBoolean();
Perfil perfil= new Perfil(nombre,apellido,intereses,visibile);
Users.add(perfil);
System.out.println("peril creado!");
ShowPerfil();
}
public static void BuscaPerfil(String nome , String cognome) {
for(int i = 0 ; i < Users.size();i++) {
if(Users.get(i).visibile != false) {
//muestra perfil
} else {
System.out.println("Este perfil es privado");
}
}
}
}
The best way to search a list
List
is by iterating through its elements and performing the search:I have changed the method so that it returns a
Profilo
. In this way, the client of the method, that is, the place where the method is used, can perform the specific action with the result of the method. The action can be: display the object's data on the screen, use it for a massive data update process, use the object to be part of another object, etc.Since Java 8, the search method can be reduced to the following:
Tips to improve your current code (not part of the main problem stated in the question).
In Java, static members (attributes and methods) belong to the class and not to the class instances (objects). If you declare an attribute as static, since the attribute belongs to the class and not to the object, then by assigning a value to said attribute, this value will be shared by all instances of the class. Therefore, in your class
Profilo
, the fields must not be static. In addition to this, all fields should have at least their getter method.The class
Profilo
should look like this:As
Users
it is anArrayList
objectprofilo
you can obtain the values in this way: