Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

세 숫자 중 가장 큰 숫자를 찾는 Java 프로그램

<시간/>

이 기사에서는 Java에서 세 정수 중 가장 큰 정수를 찾는 방법을 이해합니다. 이는 보다 큼 연산자(<)를 사용하여 수행됩니다. 여기서 우리는 값을 비교하기 위해 간단한 if-else 조건을 사용합니다.

아래는 동일한 데모입니다 -

입력

입력이 -

라고 가정합니다.
-50, 30 and 50

출력

원하는 출력은 -

The largest number is 50

알고리즘

Step1- Start
Step 2- Declare three integers: input_1, input_2 and input_3
Step 3- Prompt the user to enter the three-integer value/ define the integers
Step 4- Read the values
Step 5- Using an if else loop, compare the first input with the other two inputs to check if it is
the largest of the three integers. If not, repeat the step for the other two integers.
Step 6- Display the result
Step 7- Stop

예시 1

여기에서 입력은 프롬프트에 따라 사용자가 입력하고 있습니다. 우리코딩 그라운드 도구에서 이 예제를 라이브로 사용해 볼 수 있습니다. 세 숫자 중 가장 큰 숫자를 찾는 Java 프로그램 .

import java.util.Scanner;
public class Largest {
   public static void main(String[] args) {
      int my_input_1, my_input_2, my_input_3;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A scanner object has been defined ");
      System.out.print("Enter the first number : ");
      my_input_2 = my_scanner.nextInt();
      System.out.print("Enter the second number : ");
      my_input_2 = my_scanner.nextInt();
      System.out.print("Enter the third number : ");
      my_input_3 = my_scanner.nextInt();
      my_input_1 = -50;
      my_input_2 = 30;
      my_input_3 = 50;
      if( my_input_1 >= my_input_2 && my_input_1 >= my_input_3)
         System.out.println("The largest number is " +my_input_1);
      else if (my_input_2 >= my_input_1 && my_input_2 >= my_input_3)
         System.out.println("The largest number is " +my_input_2);
      else
         System.out.println("The largest number is " +my_input_3);
   }
}

출력

Required packages have been imported
A reader object has been defined
Enter the first number : -50
Enter the second number : 30
Enter the third number : 50
The largest number is 50

예시 2

여기서 정수는 이전에 정의되었으며 그 값은 콘솔에 액세스되어 표시됩니다.

public class Largest {
   public static void main(String[] args) {
      int my_input_1, my_input_2, my_input_3;
      my_input_1 = -50;
      my_input_2 = 30;
      my_input_3 = 50;
      System.out.println("The three numbers are defined as " +my_input_1 +", " +my_input_2 +" and " +my_input_3);
      if( my_input_1 >= my_input_2 && my_input_1 >= my_input_3)
         System.out.println("The largest number is " +my_input_1);
      else if (my_input_2 >= my_input_1 && my_input_2 >= my_input_3)
         System.out.println("The largest number is " +my_input_2);
      else
         System.out.println("The largest number is " +my_input_3);
   }
}

출력

The three numbers are defined as -50, 30 and 50
The largest number is 50