Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use many arrays object in if-else statements

It is difficult to explain about my problem, I am writing code below.

My program is like Login page with just username. I have stored Usernames as String a (As String Array). With Input as Username, and using if else statement to determine whether the Username is true or not. So how can I write code in if ( ).

I tried using

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if(b.equal(a[0])
if(b.equal(a[1])
if(b.equal(a[2])

Here it only takes 0th object from array, instead I want to include all objects from single array "a" to check in if statement.

I want

if(b.equal(Whole Objects from single array to be used at once))

The problem is difficult to explain

Here is the code below

public static void main(String[] args) {
    String[] a = {"JohnS", "SahilT", "VectorSingh"};
    String b;
    Scanner sc;

    sc = new Scanner(System.in);

    b = sc.nextLine();

    if (b.equals(a[0])) {
        System.out.println("You are welcome");
    }
    else
        System.out.println("You can't access");
}}

>Solution :

First, please declare and initialize your variables at the same time (when possible). As to your question, you need to iterate the array and check if any of the values match. You can do so by iterating explicitly, or by streaming it and testing if any of the entries match b. Like,

String[] a = { "JohnS", "SahilT", "VectorSingh" };
Scanner sc = new Scanner(System.in);
String b = sc.nextLine();
if (Arrays.stream(a).anyMatch(b::equals)) {
    System.out.println("You are welcome");
} else {
    System.out.println("You can't access");
}

Or iterating explicitly, like

String[] a = { "JohnS", "SahilT", "VectorSingh" };
Scanner sc = new Scanner(System.in);
String b = sc.nextLine();
boolean found = false;
for (String s : a) {
    if (s.equals(b)) {
        found = true;
        break;
    }
}
if (found) {
    System.out.println("You are welcome");
} else {
    System.out.println("You can't access");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading