stress_Ballz stress_Ballz - 7 months ago 11
Java Question

Using recursion to pass parameters with base cases

I am trying to complete the printConvertedNumber method to use recursion to print the first parameter in the number base specified by the second parameter. Converting to base 2,4 and 8 all use the same algorithm. The % and / operators with the desired base as the right operand are used to convert the number to the desired base. I am trying not to declare any new variables or objects in the class.

here is what it should look like, sample

Here is what I have so far, note my attempt does not work

import java.util.Scanner;

class NumberBaseConversion
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);

int number,
base;

do
{
System.out.print("Enter a positive base 10 number: ");
number = input.nextInt();
} while (number <= 0);
do
{
System.out.print("Enter a base (2, 4, or 8): ");
base = input.nextInt();
} while (base != 2 && base != 4 && base != 8);
printConvertedNumber(number, base);
System.out.println();
}

private static void printConvertedNumber(int num, int base)
{
if (base <= 0)
{
return;
}
System.out.println("num: " + num + ", base: " + base);
printConvertedNumber(num/base,num%base);
}
}


here is what i get when i run it

what i get

Answer

The problem is with your printConvertedNumber method. You're not checking once num drops below 0. Also, the recursive call to the method is a little off. Try this:

private static void printConvertedNumber(int num, int base) {
    if (num <= 0) {
        return;
    }
    printConvertedNumber(num / base, base);
    System.out.print(num % base);
}

Here are a few sample runs:

run:
Enter a positive base 10 number: 10
Enter a base (2, 4, or 8): 2
1010

run:
Enter a positive base 10 number: 4
Enter a base (2, 4, or 8): 2
100

run:
Enter a positive base 10 number: 10
Enter a base (2, 4, or 8): 8
12

run:
Enter a positive base 10 number: 10
Enter a base (2, 4, or 8): 4
22

You can check your answers against this website.