Help to search in a fix a name entered by keyboard and display the index in the one that is inside the array?

1
  ArrayList<String> nombres = new ArrayList<>();
  nombres.add("Pepe");
  nombres.add("Juan");
  nombres.add("Oscar");
    
asked by Marck 02.04.2018 в 01:37
source

2 answers

0

You can use the function indexOf that returns the index of the element if it is found, otherwise it returns -1

ArrayList<String> nombres = new ArrayList<>();
  nombres.add("Pepe");
  nombres.add("Juan");
  nombres.add("Oscar");
nombres.indexOf("Juan"); // devuelve 1
nombres.indexOf("Pedro"); // devuelve -1
    
answered by 02.04.2018 в 01:52
0

To order something by keyboard you can use Scanner e indexOf to know the position of the name in the array. I have done the code and I have commented it step by step.

Code:

import java.util.ArrayList;
import java.util.Scanner;

public class Ejemplo {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        // ArrayList de tipo String
        ArrayList<String> arreglo = new ArrayList<>();

        // Arregar nombres al ArrayList
        arreglo.add("Pepe");
        arreglo.add("Juan");
        arreglo.add("Oscar");

        // Pedir un nombre por teclado
        String nuevoNombre;
        System.out.print("Ingrese un nombre: ");
        nuevoNombre = scanner.nextLine();

        // Agregar el nuevo nombre en el ArrayList
        arreglo.add(nuevoNombre);

        // Cerrar Scanner
        scanner.close();

        // Imprimir arreglo
        for (String nombre : arreglo) {
            System.out.println(nombre);

            // Posición del nombre ingresado por teclado
            if (nombre.equals(nuevoNombre))
                System.out.println("Nombre encontrado en la posición " + arreglo.indexOf(nuevoNombre));
        }

    }
}

Output:

  

Enter a name: Maria

     

Pepe

     

Juan

     

Oscar

     

Maria

     

Name found in position 3

I hope I have helped you.

    
answered by 02.04.2018 в 02:49