How to write code in Java to compare sizes?
In Java, comparison operators (<, >, <=, >=, ==, !=) can be used to compare sizes.
Here is an example code comparing the sizes of two integers:
public class CompareNumbers {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
if (num1 > num2) {
System.out.println(num1 + " 大于 " + num2);
} else if (num1 < num2) {
System.out.println(num1 + " 小于 " + num2);
} else {
System.out.println(num1 + " 等于 " + num2);
}
}
}
Running the above code will output: 10 is less than 20, because the first number is smaller than the second number.
You can also encapsulate the above code into a method for reuse. For example:
public class CompareNumbers {
public static void compare(int num1, int num2) {
if (num1 > num2) {
System.out.println(num1 + " 大于 " + num2);
} else if (num1 < num2) {
System.out.println(num1 + " 小于 " + num2);
} else {
System.out.println(num1 + " 等于 " + num2);
}
}
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
compare(num1, num2);
}
}
In this way, you only need to call the compare() method and pass in two integers that need to be compared.