The primerjaj() metoda je metoda Integer razred Spodaj paket java.lang . Ta metoda numerično primerja dve celoštevilski vrednosti. Rezultat vrne v celoštevilski ekvivalentni vrednosti s primerjavo metode dveh int argumenti . Vrnjena vrednost je enaka tisti, ki bi jo vrnilo:
Integer.valueOf(x).compareTo(Integer.valueOf(y))
Sintaksa
Sledi izjava primerjaj() metoda:
public static int compare(int x,int y)
Parameter:
DataType | Parameter | Opis | Obvezno/izbirno |
---|---|---|---|
int | x | Prva celoštevilska vrednost za primerjavo | Obvezno |
int | in | Druga celoštevilska vrednost za primerjavo | Obvezno |
Vrne:
Ta metoda bo vrnila naslednje vrednosti:
0 = The value 0 if x == y, -1 = The value less than 0 if x y
Izjeme:
TO
Združljivostna različica:
Java 1.7 in novejši
Primer 1
public class IntegerCompareExample1 { public static void main(String[] args) { int num1 = 10; int num2 = 20; int num3 = 10; int num4 = 30; // as num1 less than num2, Output will be less than zero System.out.println(Integer.compare(num1, num2)); // as num1 equals num3, Output will be zero System.out.println(Integer.compare(num1, num3)); // as num4 is greater than num2, Output will be greater than zero System.out.println(Integer.compare(num4, num2)); } }Preizkusite zdaj
Izhod:
-1 0 1
Primer 2
import java.util.Scanner; public class IntegerCompareExample2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print('Enter the first numeric value: '); int number1 = sc.nextInt(); System.out.print('Enter the second numeric value: '); int number2 = sc.nextInt(); sc.close(); // compares two Integer values numerically int retResult = Integer.compare(number1, number2); if(retResult > 0) { System.out.println('number1 is greater than number2'); } else if(retResult<0) { system.out.println('number1 is less than number2'); } else equal to < pre> <p> <strong>Output:</strong> </p> <pre> Enter the first numeric value: 55 Enter the second numeric value: 66 number1 is less than number2 </pre> <h2>Example 3</h2> <pre> public class IntegerCompareExample3 { public static void main(String[] args) { System.out.println(Integer.compare(200, 100)); System.out.println(Integer.compare(200, 200)); System.out.println(Integer.compare(100, 150)); } } </pre> <span> Test it Now </span> <p> <strong>Output:</strong> </p> <pre> 1 0 -1 </pre> <br></0)>
Primer 3
public class IntegerCompareExample3 { public static void main(String[] args) { System.out.println(Integer.compare(200, 100)); System.out.println(Integer.compare(200, 200)); System.out.println(Integer.compare(100, 150)); } }Preizkusite zdaj
Izhod:
1 0 -1
0)>