Reputation: 91
I have a problem in this program where when I enter a correct value it gives me the correct output but it also asks me to enter my name again. It is working for when i enter an incorrect value 3 times it will terminate the program although it does not print out the error message. I am not sure how to change it so that it will only output the you are verified you may use the lift.
import java.util.Scanner;
public class Username
{
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
// array containing usernames
String [] name = {"barry", "matty", "olly","joey"}; // elements in array
boolean x;
x = false;
int j = 0;
while (j < 3)
{
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1))
{
System.out.println("you are verified you may use the lift");
x = true;
break;// to stop loop checking names
}
}
if (x = false)
{
System.out.println("wrong");
}
j++;
}
if(x = false)
{
System.out.println("Wrong password entered three times. goodbye.");
}
}}
Upvotes: 0
Views: 203
Reputation: 124215
In your if (x = false)
you are first assigning false
to x
which is then checked in condition. In other words your code is similar to
x = false;
if (x) {//...
You probably wanted to write
if (x == false) // == is used for comparisons, `=` is used for assigning
but don't use this style of coding. Instead you can use Yoda conditions
if (false == x)// Because you can't assign new value to constant you will not
// make mistake `if (false = x)` <- this would not compile
or even better
if (!x)// it is the same as `if (negate(x))` which when `x` would be false would
// mean `if (negate(false))` which will be evaluated to `if (true)`
// BTW there is no `negate` method in Java, but you get the idea
Form if(x)
is equal to if (x == true)
because
true == true
<==> true
false == true
<==> false
which means
X == true
<==> X
(where X
can be only true or false).
Similarly if (!x)
means if(x == false)
.
Upvotes: 3