mercredi 30 septembre 2020

"Name Doesn't Match" print but here it printing 5 times

When I type something which isn't there in array list, "Name Doesn't Match" is printing for 5 times. I want to make this print for only one time.

  1. Which line of code is making "Name Doesn't Match" print 5 times?
  2. how to print "Name Doesn't Match" only 1 time?
public class Arrays {
    public static void main(String[] args) {

String[] names = {"Meisam", "Raju", "Sasi", "Aju", "Ram"};
        int[] numbers = {123456, 654321, 345678, 953456, 123445};
        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i]);
        }

        System.out.println("Please Enter a Name:  ");
        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(numbers[i]);
            } else {
                System.out.println("Names Doesn't Match!");
            }
            }
        }
    }
               

Output is:

Meisam
Raju
Sasi
Aju
Ram
Please Enter a Name:  
raj //input a keyword called 'raj' 
Names Doesn't Match!
Names Doesn't Match!
Names Doesn't Match!
Names Doesn't Match!
Names Doesn't Match!

Aucun commentaire:

Enregistrer un commentaire