Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java นับจำนวนหลักของจำนวนเต็ม

ในบทความนี้ เราจะเรียนรู้วิธีนับจำนวนหลักของจำนวนเต็มในภาษา Java การนับทำได้โดยใช้ลูปและตัวนับ (counter)

ตัวอย่างการทำงาน

อินพุต:

Number : 15161718

เอาต์พุต:

The result is : 8

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. ประกาศตัวแปรจำนวนเต็ม 2 ตัว: my_count และ my_input
  3. รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
  4. ใช้ลูป for หารค่า input ด้วย 10 จนกว่าจะเหลือ 0 เพิ่มค่าตัวนับทุกครั้ง
  5. แสดงค่าตัวนับเป็นผลลัพธ์
  6. จบโปรแกรม

ตัวอย่างที่ 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 หลัก