# 用于十进制到八进制转换的 Java 程序

> 原文： [https://beginnersbook.com/2014/07/java-program-for-decimal-to-octal-conversion/](https://beginnersbook.com/2014/07/java-program-for-decimal-to-octal-conversion/)

在本教程中，我们将学习以下两种方法**将十进制数转换为等效的八进制数**。

1）使用预定义的方法 [Integer.toOctalString（int num）](https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toOctalString(int))
2）编写我们自己的转换逻辑

```java
import java.util.Scanner;
class DecimalToOctalExample
{
  public static void main(String args[])
  {
    Scanner input = new Scanner( System.in );
    System.out.print("Enter a decimal number : ");
    int num =input.nextInt();

    /* Method 1: 
     * Using predefined method toOctalString(int)
     * Pass the decimal number to this method and
     * it would return the equivalent octal number
     */
    String octalString = Integer.toOctalString(num);
    System.out.println("Method 1: Decimal to octal: " + octalString);

    /* Method 2: 
     * Writing your own logic: Here we will write
     * our own logic for decimal to octal conversion
     */

    // For storing remainder
    int rem;

    // For storing result
    String str=""; 

    // Digits in Octal number system
    char dig[]={'0','1','2','3','4','5','6','7'};

    while(num>0)
    {
       rem=num%8; 
       str=dig[rem]+str; 
       num=num/8;
    }
    System.out.println("Method 2: Decimal to octal: "+str);
  }
}
```

**输出：**

```java
Enter a decimal number : 123
Method 1: Decimal to octal: 173
Method 2: Decimal to octal: 173
```