I am a new programmer, so sorry if this is really basic. I have looked around for this website for an answer, I could find very similar questions, but none was what I needed.
import java.util.Scanner;
public class sortThreeIntegers
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
Scanner input3 = new Scanner(System.in);
System.out.println("Enter the first number: ");
System.out.println("Enter the second number: ");
System.out.println("Enter the third number: ");
double firstNumber = input.nextDouble();
double secondNumber = input2.nextDouble();
double thirdNumber = input3.nextDouble();
if (firstNumber > secondNumber > thirdNumber == true)
{
System.out.println(firstNumber + ", " + secondNumber + ", " + thirdNumber);
}
else if (firstNumber > thirdNumber > secondNumber == true)
{
System.out.println(firstNumber + ", " + thirdNumber + ", " + secondNumber);
}
}
}
Note: This is in the middle of me writing the code, I am not finished with this.
Why am I getting the error "The operator > is undefined for the argument type(s) boolean, double"? Again, sorry if this is really simple.
if (firstNumber > secondNumber > thirdNumber == true)
This is invalid; you want:
if (firstNumber > secondNumber && secondNumber > thirdNumber)
The same goes for your else if
condition.
You cannot chain comparisons in Java like you can in, say, Python. Also, there is never a need for an == true
in boolean expressions. After all, x == true
will always be x
.
The error you received makes sense, since your expression is being evaluated as:
(firstNumber > secondNumber) > thirdNumber
Now (firstNumber > secondNumber)
is a boolean, which cannot be compared to a double (thirdNumber
).
Finally, it looks like you're just trying to output the numbers in sorted order. Why not just sort them regularly, then output the result? Also: don't use three different scanners! Just use the same one three times.
This is what I mean by sorting the numbers:
double numbers[] = {firstNumber, secondNumber, thirdNumber};
Arrays.sort(numbers);
System.out.println(numbers[2] + ", " + numbers[1] + ", " + numbers[0]);
You cannot combine operators such as >
as we would do as a shortcut in expressing a mathematical inequality. You must list out such expression explicitly and join the expressions with the &&
and operator.
if (firstNumber > secondNumber && secondNumber > thirdNumber) {
Also, I took out the unnecessary comparison to true
, because the result of the >
(and other comparison operators) is already a boolean
.
You can change your else if
condition similarly.
You can't have this : if (firstNumber > secondNumber > thirdNumber == true)
.
You need to break it down to:
if (firstNumber > secondNumber && secondNumber > thirdNumber) {