Home > Back-end >  is there a simple way to write this code?
is there a simple way to write this code?

Time:10-29

this java code, to know which number higher

import java.util.Scanner;
public class MyClass {
    public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    int angkaPertama, angkaKedua, angkaKetiga;

    System.out.print("Masukkan angka pertama : ");
    angkaPertama = sc.nextInt();
    System.out.print("Masukkan angka kedua : ");
    angkaKedua = sc.nextInt();
    System.out.print("Masukkan angka ketiga : ");
    angkaKetiga = sc.nextInt();
    
    if(angkaPertama > angkaKedua && angkaPertama > angkaKetiga){
        System.out.println("Angka terbesar : " angkaPertama);
    }else if(angkaKedua > angkaPertama && angkaKedua > angkaKetiga){
        System.out.println("Angka terbesar : " angkaKedua);
    }else if(angkaKetiga > angkaPertama && angkaKetiga > angkaKedua){
        System.out.println("Angka terbesar : " angkaKetiga);
    }        
}
}

I just want to know if the comparison can be simpler.

CodePudding user response:

You could factorize the scanner but with only 3 use of it, you would get no gain of line, maybe even 1 or 2 line more..

But if you wanted to use the scanner some more, Factorize it would certainly be a gain of time and codeline

CodePudding user response:

I would use successive calls to Math.max(int, int) like

Scanner sc = new Scanner(System.in);

System.out.print("Masukkan angka pertama : ");
int angkaPertama = sc.nextInt();
System.out.print("Masukkan angka kedua : ");
int angkaKedua = sc.nextInt();
System.out.print("Masukkan angka ketiga : ");
int angkaKetiga = sc.nextInt();
System.out.printf("Angka terbesar : %d%n", 
        Math.max(Math.max(angkaPertama, angkaKedua), angkaKetiga));
  •  Tags:  
  • java
  • Related