This site requires JavaScript, please enable it in your browser!
Greenfoot back
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");
Sytem.out.println("Enter your password");
if(name.indexOf(enterName) == password.indexOf(enterPass))
//Trying to check whether hadrik is equal to hadrik123 
else System.out.println("incorrect");
Can anyone tell me why it is not working
danpost danpost

4 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.