dimanche 3 novembre 2019

I do not know how to use the else statement in this array method to print out what happens if the if statement condition is false [duplicate]

This question already has an answer here:

This is the main method:

public static void main(String [] args) {

    String arr [] = {"John", "Rose", "Nathan", "Sina", "Irene", "Mina", "Samuel" };


 array(arr,7,"Samuel");

This is the void method:

public static void array (String A[], int length, String elementiwant) {

    for(int i = 0; i < length; i++) {

        if(A[i] == elementiwant) {

            System.out.println("Your element is : " + elementiwant);

        } else {

           System.out.println("Your element is not in the array.");            

       }
    }   
}

This is what gets printed out in the console:

Your element is not in the array.
Your element is not in the array.
Your element is not in the array.
Your element is not in the array.
Your element is not in the array.
Your element is not in the array.
Your element is : Samuel

and if i use the print method outside of the for loop this will show on the console:

Your element is : Samuel
Your element is not in the array.

I want to be able to print the else statement when the if statement condition is false and not when the if statement condition is true. How do i correct this program?

Aucun commentaire:

Enregistrer un commentaire