The first thing you should do is create a book class, that hosts all the corresponding attributes (name, author and naturalness)
Book:
public class Libro {
String nombre, autor, naturalidad;
public Libro() {
}
public Libro(String nombre, String autor, String naturalidad) {
super();
this.nombre = nombre;
this.autor = autor;
this.naturalidad = naturalidad;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getAutor() {
return autor;
}
public void setAutor(String autor) {
this.autor = autor;
}
public String getNaturalidad() {
return naturalidad;
}
public void setNaturalidad(String naturalidad) {
this.naturalidad = naturalidad;
}
@Override
public String toString() {
return "Libro [nombre=" + nombre + ", autor=" + autor + ", naturalidad=" + naturalidad + "]";
}
}
Then, you can implement a flow to add books, and create a method to search by name and print the data (with the toString method overloaded previously):
import java.util.ArrayList;
import java.util.Scanner;
public class Proceso {
public static void main(String[] args) {
ArrayList<Libro> listaLibros = new ArrayList<Libro>();
Scanner sc = new Scanner(System.in);
System.out.println("Cuántos libros desea ingresar:");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
sc.nextLine();
Libro lib = new Libro();
System.out.println("Ingrese el nombre del libro:");
lib.setNombre(sc.nextLine());
System.out.println("Ingrese el nombre del autor:");
lib.setAutor(sc.nextLine());
System.out.println("Ingrese la naturalidad del libro:");
lib.setNaturalidad(sc.nextLine());
listaLibros.add(lib);
}
System.out.println("Ingrese nombre libro a buscar: ");
Libro buscado = findByName(sc.nextLine(), listaLibros);
if (buscado == null) {
System.out.println("Libro no encontrado");
} else {
System.out.println(buscado.toString());
}
}
public static Libro findByName(String nombreLibro, ArrayList<Libro> listaLibros) {
for (Libro libro : listaLibros) {
if (libro.getNombre().equals(nombreLibro)) {
return libro;
}
}
return null;
}
}
Execution examples:
Cuántos libros desea ingresar:
1
Ingrese el nombre del libro:
1
Ingrese el nombre del autor:
2
Ingrese la naturalidad del libro:
3
Ingrese nombre libro a buscar:
2
Libro no encontrado
Cuántos libros desea ingresar:
1
Ingrese el nombre del libro:
1
Ingrese el nombre del autor:
2
Ingrese la naturalidad del libro:
3
Ingrese nombre libro a buscar:
1
Libro [nombre=1, autor=2, naturalidad=3]