Testing if an inputted String exists in an String Array
Ok,
So what i want to do is read in a String from the user and test to see if the inputted String is equal to one of the Strings that exist in a String array that i have created.
Here is what i have:
Code :
public class task13 {
public static void main(String[] args) {
String[] passwords = new String[]{"rose77", "2today", "5staff"};
Scanner scan = new Scanner(System.in);
System.out.println("Enter a valid company password: ");
String input = scan.nextLine();
[B] if (input is equal to one of the Strings in the String Array)
then execute this
else ...........................[/B]
}
}
I have highlighted the bold part which is where i am stuck im not sure which class or method i need to use.
Re: Testing if an inputted String exists in an String Array
Look at the String class. It has several methods for comparing Strings.
You will need a loop that accesses each element in the array and tests that element.
You'll also need a way to remember the results when the code exits the loop so the following code can react as needed.
Re: Testing if an inputted String exists in an String Array
Ok cheers,
had a quick look around and a quick think and only thing i came up with is this:
Code :
public static void main(String[] args) {
String[] passwords = new String[]{"rose77", "2today", "5staff"};
Scanner scan = new Scanner(System.in);
System.out.println("Enter a valid company password: ");
String input = scan.nextLine();
if (input.equals(passwords[0])){
System.out.println("Password Validated");
}
else if (input.equals(passwords[1])){
System.out.println("Password Validated");
}
else if (input.equals(passwords[2])){
System.out.println("Password Validated");
}
else {
System.out.println("Invalid Password!");
}
}
}
As you can see it checks each index of the String array one by one using the .equals() method.
My only concern with this way is that if there were 100 items in the Array, that would one hell of an if-else statement to type out and check each individual one.
So i'm wondering is there a more practical way of doing it ?
Re: Testing if an inputted String exists in an String Array
The code needs to use a for loop with an index variable. It should NOT index each element by explicit index.
Code :
if (input.equals(passwords[0])){
[0] is the wrong way to do it. Put the test in a loop and use the loop's variable: [i]
You seem to have missed most of what I said in post#2