Trong bài viết này, chúng ta sẽ tìm hiểu cách tìm số lớn nhất trong ba số nguyên trong Java. Việc này dùng toán tử so sánh lớn hơn (>). Ta sử dụng câu lệnh if-else đơn giản để so sánh.
Dưới đây là minh họa:
Đầu vào
Giả sử đầu vào:
-50, 30 và 50
Đầu ra
Kết quả mong đợi:
Số lớn nhất là 50
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo ba số nguyên: input_1, input_2, input_3 Bước 3 - Nhập ba số từ người dùng hoặc định nghĩa trước Bước 4 - Đọc giá trị Bước 5 - Dùng if-else so sánh input_1 với hai số còn lại. Nếu không phải lớn nhất, lặp lại cho hai số khác. Bước 6 - Hiển thị kết quả Bước 7 - DỪNG
Ví dụ 1: Nhập từ bàn phím
Người dùng nhập dựa trên lời nhắc. Thử trực tiếp trong coding ground.
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_1 = 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();
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);
}
}
Đầu ra
Required packages have been imported A scanner object has been defined Enter the first number: -50 Enter the second number: 30 Enter the third number: 50 The largest number is 50
Ví dụ 2: Giá trị định nghĩa trước
Ba số đã được định nghĩa trước.
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);
}
}
Đầu ra
The three numbers are defined as -50, 30 and 50 The largest number is 50