This site requires JavaScript, please enable it in your browser!
Greenfoot back
mik.
mik. wrote ...

4 days ago

Get the index of an array

mik. mik.

4 days ago

#
String name[]={"john", "hadrik", "peter", "rodrick"};
String password []={"john", "hadrik123", "peter987", "rodrick"};
System.out.println("Enter your name");
String enterName=sc.next();
Sytem.out.println("Enter your password");
string enterPass=sc.next();
if(name.indexOf(enterName) == password.indexOf(enterPass))
//Trying to check whether hadrik is equal to hadrik123 
System.out.println("correct");
else System.out.println("incorrect");
Can anyone tell me why it is not working
danpost danpost

3 days ago

#
I see two issues. First one is that line 6 should start with "String". not "string". Second issue is that the arguments of "indexOf" for the array elements will NOT be the same String object as that with the same content (character sequence) as what is entered via the scanner. Since what is being indexed is NOT the same object as what is in the array, the returned index will be "-1", meaning the object is not in the array. You will have to go through the array, one element at a time, to check the character sequences for equality:
boolean correct = false;
for (int i=0; i<name.length; i++)
{
    if (name[i].equals(enterName) && password[i].equals(enterPass)) correct = true;
}
System.out.println(correct ? "correct" : "incorrect");
mik. mik.

3 days ago

#
Thank you
You need to login to post a reply.