ในบทความนี้ เราจะเรียนรู้วิธีนับจำนวนหลักของจำนวนเต็มในภาษา Java การนับทำได้โดยใช้ลูปและตัวนับ (counter)
ตัวอย่างการทำงาน
อินพุต:
Number : 15161718
เอาต์พุต:
The result is : 8
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปรจำนวนเต็ม 2 ตัว:
my_countและmy_input - รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
- ใช้ลูป
forหารค่า input ด้วย 10 จนกว่าจะเหลือ 0 เพิ่มค่าตัวนับทุกครั้ง - แสดงค่าตัวนับเป็นผลลัพธ์
- จบโปรแกรม
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int my_count = 0, my_input;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined");
System.out.print("Enter the number: ");
my_input = my_scanner.nextInt();
for (; my_input != 0; my_input /= 10, ++my_count) {
// ลูปว่าง - การทำงานอยู่ในเงื่อนไขของ for loop
}
System.out.println("The number of digits in the given input is: " + my_count);
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class Main {
public static void main(String[] args) {
int my_count = 0, my_input = 15161718;
System.out.println("The number is defined as " + my_input);
for (; my_input != 0; my_input /= 10, ++my_count) {
}
System.out.println("The number of digits in the given input is: " + my_count);
}
}
ทั้งสองตัวอย่างจะให้ผลลัพธ์เป็น 8 หลัก