1

I was Created a String Array of names and Int array for the Phone Number and asking the user to select the names from the list of array and we want to display the exact number of the name

public class main {

public static void main(String[] args) {
    String[] names = {"Name one  ","Name two ","name three ","Four"};
    int[] num ={12345,56789,25622,21478};
    for (int i = 0;i < names.length;i++)
    {
        System.out.println(names[i]);

    }
    System.out.println("Enter the Name To get Numbers");
    Scanner scanner = new Scanner(System.in);
    String name=scanner.next();
    for (int i=0; i <names.length; i++)
    {
        if (name.equals(names[i]));
        {
            System.out.println(num[i]);
        }

    }
    

}

the output what i get was

Name one  
Name two 
name three 
Four
Enter the Name To get Numbers
Four
12345
56789
25622
21478

Process finished with exit code 0

what ever name i enter it displays all the numbers in the array how to solve this ? The Output what i Need was

Name one  
    Name two 
    name three 
    Four
    Enter the Name To get Numbers
    Four
    21478
1
  • 3
    You have a semicolon at the end of the if condition. Commented Jul 18, 2020 at 6:11

1 Answer 1

3

You have a semicolon at the end of the if condition. Remove that and your code will work fine.

if (name.equals(names[i])) {
        System.out.println(num[i]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, why it goes in loop when i out Semicoln ? can u explain pls it was better to undestanf
See this post for explanation
if the user Input is not in the array list of names means we want to say to the user to choose names in the array for that i use else statement at the end of the if and run it was display choose the names in loop if i enter a wrong array , even if i use break it doesnot stop how to solve this
An else will be executed for each if. Have a boolean flag set to false. Set it to true inside the if. Then after the for loop is done, check if that boolean is still false. If yes, then print that none of the names had a match with what the user had entered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.