ในบทความนี้ เราจะเรียนรู้วิธีหาตัวเลขมากที่สุดใน 3 จำนวนเต็มในภาษา Java ใช้ตัวดำเนินการมากกว่า (>) และเงื่อนไข if-else
ตัวอย่างการทำงาน
อินพุต:
-50, 30 and 50
เอาต์พุต:
The largest number is 50
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปรจำนวนเต็ม 3 ตัว:
input_1,input_2,input_3 - รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
- ใช้ if-else เปรียบเทียบ input_1 กับอีก 2 ตัว, ถ้าไม่ใช่ ตรวจสอบ input_2, ไมใช่ก็ input_3
- แสดงผลลัพธ์
- จบโปรแกรม
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
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);
}
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class Largest {
public static void main(String[] args) {
int 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);
}
}
}
วิธีทางเลือก: ใช้ Math.max
int max = Math.max(my_input_1, Math.max(my_input_2, my_input_3));
System.out.println("The largest number is " + max);
วิธี Math.max เขียนสั้นกว่าและอ่านง่ายกว่า แนะนำให้ใช้ในโค้ดจริง