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
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");
}