使用for循环将十进制转换为八进制

时间:2016-01-30 05:58:13

标签: java

我的for循环遇到了麻烦。 for循环应该将十进制转换为八进制。有人可以指出我做错了什么。

import java.util.Scanner;

public class Dboh {

 public static void main(String[] args) {

     Scanner input = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int decimal = input.nextInt();
        int single;
        int val;

        //Binary
        String binaryString = "";
        int value = decimal;
        while (value != 0) {
        binaryString = value % 2 + binaryString;
        value = value / 2;
        }

       //Octal
        String octalString = "";
        for (decimal = val, single = val % 8, octalString = single + octalString, val = val / 8) {


        //Hexadecimal


        System.out.println("Decimal" + "\t" + "Binary" + "\t" + "Octal" +       "\t" + "Hexadecimal");
        System.out.println(decimal + "\t" + binaryString + "\t" + octalString);

1 个答案:

答案 0 :(得分:2)

像这样改变你的for循环

val = decimal

而不是

decimal = val



for(val = decimal; val > 0; val = val / 8){
octalString = val % 8 + octalString;
}