Search code examples
javaposition

How to print out the position of this name in the list?


Hi developers on Stackoverflow! I have a problem on this exercise: "Write a program that asks user to input a list of N names using the keyboard, then user continues inputting a name for searching. The program should print out the position of this name in the list. In case the name doesn’t appear in the list, the program should print out value -1." Here is my code:

package Tut_01;

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

public class Ex_04 {
    public static void main(String[] args) {
        Scanner sc = new Scanner (System.in);
        ArrayList<String> elements = new ArrayList<> ();
        System.out.print ("How many numbers do you want to input: ");
        int n = sc.nextInt (); // Count numbers that user want to input

        // Ask the user input values

        for (int i = 0; i < n; i++) {
            System.out.print ("Enter your name " + (i + 1) + ": ");
            String name = sc.next ();
            elements.add (name);
        }

        System.out.println ("Which name do you want to search ?");
        String searchName = sc.next ();

        // Problem?
        for (int p = 0; p < n; p++) {
            if (searchName == elements.get (p)) {
                System.out.println ("Your name is at index " + p + ": " + elements.get (p));
            }
        }

    }

Here is my console:

How many numbers do you want to input: 2
Enter your name 1: Hoa
Enter your name 2: Hieu
Which name do you want to search ?
Hoa

Process finished with exit code 0

I mean I don't know why my code stops there instead of printing the position of the index. Anyone knows this issue? Thanks for showing me!


Solution

  • You are comparing String in the wrong way. String is an object not a primitive, so you cannot use ==.

    The proper way is:

    searchName.equals(elements.get(p))