简体   繁体   中英

Coverting a decimal to binary using for loops?

I'm trying to write a program that converts decimal to binary and decimal to octal. I can convert from decimal to binary, but from decimal to octal it just doesn't work.

import java.util.*;
public class RadixConversion 
{
public static void main(String[] args) 
{
Scanner scan = new Scanner(System.in);    
System.out.println("Enter a number: ");
int number = scan.nextInt();
System.out.println("Convert to base: ");
String letter = scan.next();

if (letter.equals("b")||letter.equals("B"))
    {
        int remainder = 0;
        for (int i = 1; number > 0; i++) 
        {
        number /= 2;
        remainder = number % 2;
        System.out.print(remainder);
        }
    }


    else if (letter.equals ("o") || letter.equals ("O"))
    {
        int remainder = 0;
        for (int i = 1; number >0 ; i++) 
        {
        number /= 8;
        remainder = number % 8;
        System.out.print(remainder);
        }
    }
 }        
 }

This is a bit more complicated the way I learned it. You have to find the largest power of 8 that fits in the number, see how many times it goes into the number, and repeat the process with the next lowest power of 8. You print each digit as you go.

neither one looks to be generating the correct value, it would just be less obvious with 0's and 1's. You are dropping the first digit and printing the digits in reverse order (the one's digit get printed first)

    int remainder = 0;
    String result = "";
    for (int i = 1; number >0 ; i++) 
    {
      remainder = number % 8;
      result = remainder + result;  // remainder first puts the digits in the right order
      number /= 8;
    }
    System.out.print(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM