Giải Bài Convert Binary, Octal, Hexadecimal to Decimal – Java LAB211 FPT

Chào anh em! Trong lộ trình học LAB211 Java OOP tại FPT, mỗi bài lab đều mang đến một chủ đề giúp ta vừa ôn lại kiến thức lý thuyết vừa áp dụng ngay vào thực hành. Với bài Convert Binary, Octal, Hexadecimal to Decimal, chúng ta sẽ bước vào thế giới của các hệ đếm quen thuộc trong toán học và điện tử số.

Nhiệm vụ của bạn là viết chương trình cho phép người dùng nhập vào số ở hệ binary, octal hoặc hexadecimal, sau đó chuyển đổi chính xác sang decimal và in ra màn hình. Nghe có vẻ đơn giản, nhưng qua đó bạn sẽ luyện thêm kỹ năng thao tác với chuỗi nhập liệu, xử lý menu console và nắm rõ hơn cách Java hỗ trợ chuyển đổi cơ số. Đây chắc chắn là một mảnh ghép quan trọng trong series LAB211 mà TruongDevs chia sẻ cùng các bạn.

convert binary, octal, hexadecimal to decimal java lab211 fpt
Giải bài Convert Binary, Octal, Hexadecimal to Decimal Java OOP LAB211 FPT

Mục tiêu bài lab Convert Binary, Octal, Hexadecimal to Decimal (LAB211 FPT)

  • Ôn tập kiến thức về các hệ đếm phổ biến trong toán học và điện tử số: binary, octal, hexadecimal và decimal.
  • Luyện kỹ năng nhập dữ liệu từ bàn phím và kiểm tra tính hợp lệ của dữ liệu.
  • Viết chương trình có menu cho phép lựa chọn: chuyển đổi từ binary, octal hoặc hexadecimal sang decimal.
  • Hiển thị kết quả chuyển đổi rõ ràng trên màn hình.
  • Tăng khả năng tư duy lập trình với Java console và xử lý tình huống bằng câu lệnh điều khiển.

Đề bài gốc – Convert Binary, Octal and Hexadecimal to Decimal (LAB211)

Title:
Convert binary, octal and hexadecimal to decimal

Background Context:
In mathematics and digital electronics, a binary number is a number expressed in the binary numeral system or base-2 numeral system which represents numeric values using two different symbols: typically 0 (zero) and 1 (one). The base-2 system is a positional notation with a radix of 2. Because of its straightforward implementation in digital electronic circuitry using logic gates, the binary system is used internally by almost all modern computers and computer-based devices. Each digit is referred to as a bit.

The octal numeral system, or oct for short, is the base-8 number system, and uses the digits 0 to 7. The hexadecimal (also base 16, or hex) is a positional numeral system with a radix, or base, of 16. It uses sixteen distinct symbols, most often the symbols 0–9 to represent values zero to nine, and A, B, C, D, E, F (or alternatively a, b, c, d, e, f) to represent values ten to fifteen. Hexadecimal numerals are widely used by computer system designers and programmers.

Program Specifications:
Create a program to convert binary, octal and hexadecimal to decimal.

Function details:
1. Enter a binary/octal/hexadecimal number
2. Convert the binary/octal/hexadecimal number to decimal number
3. Display the decimal number on the screen

Expectation of User Interface:
1. Convert binary number to decimal number
2. Convert octal number to decimal number
3. Convert hexadecimal number to decimal number
4. Exit
Please choose number (1 – 4): 1
Enter binary number: 0011010
Decimal number is: 26

Guidelines:
Student study relationship between binary/octal/hexa number and decimal number

Source Code – Convert Binary, Octal, Hexadecimal to Decimal (LAB211 FPT)

Dưới đây là full source code project Convert Binary, Octal, Hexadecimal to Decimal viết bằng Java, bạn có thể copy về chạy trực tiếp trong NetBeans hoặc IntelliJ:

📁 SE1905S03.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package se1905s03;

import java.util.Scanner;

/**
 * S03 - Convert binary, octal and hexadecimal to decimal
 *
 * @author TruongNTCE180140
 */
public class SE1905S03 {

    /**
     * The main method
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        MyLib S03 = new MyLib();
        S03.run();
    }
}

📁 MyLib.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package se1905s03;

import java.util.Scanner;

/**
 * S03 - Convert binary, octal and hexadecimal to decimal
 *
 * @author TruongNTCE180140
 */
public class MyLib {

    // Scanner object for user input
    Scanner sc = new Scanner(System.in);

    /**
     * Converts a binary number (string) to decimal.
     *
     * @param binaryInput Binary number as a string.
     * @return Decimal equivalent of the binary number.
     */
    private int convertBinToDec(String binaryInput) {
        int decimalNumber = 0;
        for (int i = 0; i < binaryInput.length(); i++) {
            char binaryDigit = binaryInput.charAt(i);
            if (binaryDigit == '1') { // If the digit is '1', add its value
                decimalNumber += Math.pow(2, binaryInput.length() - 1 - i);
            }
        }
        return decimalNumber;
    }

    /**
     * Converts an octal number (string) to decimal.
     *
     * @param octalInput Octal number as a string.
     * @return Decimal equivalent of the octal number.
     */
    private int convertOctToDec(String octalInput) {
        int decimalNumber = 0;
        for (int i = 0; i < octalInput.length(); i++) {
            char octalDigit = octalInput.charAt(i);
            decimalNumber += (octalDigit - '0') * Math.pow(8, octalInput.length() - 1 - i);
        }
        return decimalNumber;
    }

    /**
     * Converts a hexadecimal number (string) to decimal.
     *
     * @param hexInput Hexadecimal number as a string.
     * @return Decimal equivalent of the hexadecimal number.
     */
    private int convertHexToDec(String hexInput) {
        int decimalNumber = 0;
        for (int i = 0; i < hexInput.length(); i++) {
            char hexDigit = hexInput.charAt(i);
            if (hexDigit >= '0' && hexDigit <= '9') { // If the digit is 0-9
                decimalNumber += (hexDigit - '0') * Math.pow(16, hexInput.length() - 1 - i);
            } else if (hexDigit >= 'A' && hexDigit <= 'F') { // If the digit is A-F
                decimalNumber += (hexDigit - 'A' + 10) * Math.pow(16, hexInput.length() - 1 - i);
            }
        }
        return decimalNumber;
    }

    /**
     * Reads and validates a binary number from user input.
     *
     * @return Valid binary number as a string.
     */
    public String enterBinary() {
        String binaryInput;
        while (true) {
            System.out.print("Enter a binary number: ");
            binaryInput = sc.nextLine().trim();
            if (binaryInput.isEmpty()) {
                System.out.println("Input cannot be empty.");
            } else if (!binaryInput.matches("[01]+")) { // Validate only contains 0 and 1
                System.out.println("Invalid input. Enter a binary number (0 or 1).");
            } else {
                break;
            }
        }
        return binaryInput;
    }

    /**
     * Reads and validates an octal number from user input.
     *
     * @return Valid octal number as a string.
     */
    public String enterOctal() {
        String octalInput;
        while (true) {
            System.out.print("Enter an octal number: ");
            octalInput = sc.nextLine().trim();
            if (octalInput.isEmpty()) {
                System.out.println("Input cannot be empty.");
            } else if (!octalInput.matches("[0-7]+")) { // Validate only contains digits 0-7
                System.out.println("Invalid input. Enter an octal number (0-7).");
            } else {
                break;
            }
        }
        return octalInput;
    }

    /**
     * Reads and validates a hexadecimal number from user input.
     *
     * @return Valid hexadecimal number as a string.
     */
    public String enterHexadecimal() {
        String hexInput;
        while (true) {
            System.out.print("Enter a hexadecimal number: ");
            hexInput = sc.nextLine().trim().toUpperCase();
            if (hexInput.isEmpty()) {
                System.out.println("Input cannot be empty.");
            } else if (!hexInput.matches("[0-9A-F]+")) { // Validate only contains valid characters
                System.out.println("Invalid input. Enter a hexadecimal number (0-9, A-F).");
            } else {
                break;
            }
        }
        return hexInput;
    }

    /**
     * Displays the menu and processes user choices.
     */
    public void run() {
        while (true) {
            System.out.println("1. Convert a binary number to a decimal number");
            System.out.println("2. Convert an octal number to a decimal number");
            System.out.println("3. Convert a hexadecimal number to a decimal number");
            System.out.println("4. Exit");

            int choice = 0;
            boolean validChoice = false;

            // Loop to get a valid choice from the user
            do {
                System.out.print("Please choose an option (1-4): ");
                String input = sc.nextLine().trim();
                if (input.isEmpty()) {
                    System.out.println("Input cannot be empty. Enter a number between 1 and 4.");
                    continue;
                }
                if (!input.matches("\\d+")) { // Ensure the input is numeric
                    System.out.println("Invalid input. Enter a number between 1 and 4.");
                    continue;
                }
                try {
                    choice = Integer.parseInt(input); // Convert string to integer
                    if (choice >= 1 && choice <= 4) {
                        validChoice = true;
                    } else {
                        System.out.println("Enter a number between 1 and 4.");
                    }
                } catch (NumberFormatException e) {
                    System.out.println("Invalid input. Enter a number between 1 and 4.");
                }
            } while (!validChoice);

            // Process user choice
            switch (choice) {
                case 1:
                    String binaryInput = enterBinary();
                    System.out.println("Decimal number: " + convertBinToDec(binaryInput));
                    break;
                case 2:
                    String octalInput = enterOctal();
                    System.out.println("Decimal number: " + convertOctToDec(octalInput));
                    break;
                case 3:
                    String hexadecimalInput = enterHexadecimal();
                    System.out.println("Decimal number: " + convertHexToDec(hexadecimalInput));
                    break;
                case 4:
                    sc.close();
                    System.exit(0);
                    break;
                default:
                    System.out.println("Enter a number between 1 and 4.");
            }
        }
    }
}
Open Source! Hãy click vào từng folder để xem được code nhé anh em.

Ngoài bài Convert Binary, Octal, Hexadecimal to Decimal, trong series LAB211 Java OOP trên TruongDevs bạn có thể tham khảo thêm:

Giải Bài Reverse a String – Java OOP (LAB211 – FPT)

Giải Bài Insert New Element Into Sorted Array – Java OOP (LAB211 – FPT)

Giải Bài Candidate Management System – Java OOP (LAB211 – FPT)

Kết luận

Bài lab Convert Binary, Octal, Hexadecimal to Decimal LAB211 FPT không chỉ giúp bạn làm quen với cách xử lý dữ liệu theo nhiều hệ cơ số khác nhau mà còn rèn luyện khả năng sử dụng Scanner, vòng lặpxử lý ngoại lệ trong Java. Đây là nền tảng quan trọng để sau này bạn có thể tự tin hơn khi làm việc với dữ liệu nhị phân, hệ số 8 hay hệ 16 trong các ứng dụng thực tế.

Nếu bạn đang học LAB211 Java OOP tại FPT hoặc muốn tự ôn tập, hãy lưu lại project này để luyện tập. Đừng quên theo dõi series trên TruongDevs để cập nhật thêm nhiều bài giải lab kèm source code chi tiết nhé!

Thông tin! Mình có nhận giải lab thuê, hỗ trợ project, fix bug, training nhanh cho các môn ngành kỹ thuật từ toán đến lập trình phù hợp sinh viên FPT học đúng tiến độ.
Cam kết uy tín - đúng deadline - bảo mật tuyệt đối.
Liên hệ: Zalo.me/0973898830

About the author

Yuzu Tips
Tôi là học sinh cấp 3

Đăng nhận xét