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
Karthickyuvan
  • 428
  • 2
  • 16

1 Answers1

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]);
}
Thiyagu
  • 17,362
  • 5
  • 42
  • 79
  • 1
    thanks, why it goes in loop when i out Semicoln ? can u explain pls it was better to undestanf – Karthickyuvan Jul 18 '20 at 06:15
  • 1
    See [this post](https://stackoverflow.com/questions/32508731/what-happens-when-if-statement-is-ended-with-a-semi-colon) for explanation – Thiyagu Jul 18 '20 at 06:18
  • 2
    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 – Karthickyuvan Jul 18 '20 at 06:37
  • 1
    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. – Thiyagu Jul 18 '20 at 06:41