The user enters 3 numbers and I’m assuming all are proper integers and distinct. I’m trying to get the program to print out a sequence starting from the number of the lowest value to the highest value. Why doesn’t my else if work here? Or am I making some glaring mistake in the code?
The code is not complete, I’ve only written this far and then tested it. When I input 8 then 2 and then 4, I intend it to print out 2,3,4,5,6,7,8, but it doesn’t. Instead it prints out 4,5,6,7,8,
System.out.print("Enter a number: ");
int n1 = Integer.parseInt(in.readLine());
System.out.print("Enter a number: ");
int n2 = Integer.parseInt(in.readLine());
System.out.print("Enter a number: ");
int n3 = Integer.parseInt(in.readLine());
if ((n1 > n2) | (n2 > n3)) {
for (int i = n3; (i <= n1); i++) {
System.out.print(i + ",");
}
}
else if ((n1 > n3) | (n3 > n2)) {
for (int i = n2; (i <= n1); i++) {
System.out.print(i + ",");
}
}
}
}
Presumably, in your first condition, you want to say “n1 is greater than n2, and n2 is greater than n3”. However, the “and” operator is written as
&&, not as|(which is a bit-level “or” operator). Thus, your first condition (n1 > n2) is sufficient to satisfy the firstif, soelsedoesn’t apply.