logo

Java Pitkä vertaa() -menetelmä

Java Long -luokan vertaa()-menetelmää käytetään vertaamaan kahta pitkää objektia numeerisesti.

verkkoselaimen asetukset

Syntaksi:

 public static int compare(long x, long y) 

Parametri:

Yllä oleva menetelmä koostuu kahdesta parametrista:

  1. Ensimmäinen pitkä arvo, jota on verrattava.
  2. Toinen pitkä arvo, jota on verrattava.

Palata:

Yllä oleva menetelmä palauttaa:

  1. 0, jos x==y.
  2. Arvo on pienempi kuin 0, jos x
  3. Arvo on suurempi kuin 0, jos x>y.

Esimerkki 1

 public class JavaLongcompareExample1 { public static void main(String[] args) { Long s1 = 76l; Long s2 = 42l; int obj = Long.compare(s1, s2); if(obj==0) { System.out.println('Both the long values are same.'); } else if(obj>0) { System.out.println('The value ''+s1+'' is greater than '+s2); } else { System.out.println('The value ''+s1+'' is smaller than '+s2); } } } 
Testaa nyt

Lähtö:

 The value '76' is greater than 42 

Esimerkki 2

 import java.util.Scanner; public class JavaLongcompareExample2 { public static void main(String[] args) { Long age = 18l; Scanner scanner = new Scanner(System.in); System.out.print(&apos;Enter your valid age: &apos;); Long userAge = scanner.nextLong(); int com = Long.compare(age,userAge); if(com<=0) { system.out.println('you are eligible to vote.'); } else not eligible.'); < pre> <p> <strong>Output:</strong> </p> <pre> Enter your valid age: 35 You are eligible to vote. </pre> <h2>Example 3</h2> <pre> import java.util.Scanner; public class JavaLongcompareExample3 { public static void main(String[] args) { Long doy = 2018l; Scanner scanner = new Scanner(System.in); System.out.print(&apos;Enter your birth year : &apos;); Long userAge = scanner.nextLong(); int com = Long.compare(doy,userAge); if(com<=0) { system.out.println('please enter a valid birth year.'); } else long age="doy-userAge;" system.out.println('you are '+age+' years old.'); < pre> <p> <strong>Output:</strong> </p> <pre> Enter your birth year : 2020 PLEASE enter a valid birth year. </pre></=0)></pre></=0)>

Esimerkki 3

 import java.util.Scanner; public class JavaLongcompareExample3 { public static void main(String[] args) { Long doy = 2018l; Scanner scanner = new Scanner(System.in); System.out.print(&apos;Enter your birth year : &apos;); Long userAge = scanner.nextLong(); int com = Long.compare(doy,userAge); if(com<=0) { system.out.println(\'please enter a valid birth year.\'); } else long age="doy-userAge;" system.out.println(\'you are \'+age+\' years old.\'); < pre> <p> <strong>Output:</strong> </p> <pre> Enter your birth year : 2020 PLEASE enter a valid birth year. </pre></=0)>