0

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!

Hòa Đỗ
  • 37
  • 8
  • 1
    Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – akuzminykh Mar 21 '20 at 08:45

2 Answers2

1

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))
reuseman
  • 323
  • 1
  • 6
  • 19
  • Yes, I see. Thanks for your help! – Hòa Đỗ Mar 21 '20 at 08:58
  • But how can the program print out -1 when I input a name that doesn't exist on a list? – Hòa Đỗ Mar 21 '20 at 09:11
  • @HòaĐỗ Before the for-loop you can instantiate an int variable to -1, called indexFound. In the for-loop if the name matches one in the list you update the index. At the end of the loop you can do the check to see if you found something or not – reuseman Mar 21 '20 at 09:13
0

Below the simple code will give the same output.Make use of indexOf method

System.out.println("Your name is at index " + elements.indexOf(searchName) + ": " + searchName);