Gabbie Grapes - 7 months ago 52

Java Question

I am working on a code that is supposed to take in a users input, then convert it to binary with base 2 through 9. (Sorry if these are the wrong terms, completely new to the idea of binary.) I have the code done, but there is something missing. This is what it is supposed to out put when the user types in "245"

`converted to base 2 = 11110101`

converted to base 3 = 100002

converted to base 4 = 3311

converted to base 5 = 1440

converted to base 6 = 1045

converted to base 7 = 500

converted to base 8 = 365

converted to base 9 = 302

However, this is what I get for my output:

`converted to base 2 = 1111010`

converted to base 3 = 10000

converted to base 4 = 331

converted to base 5 = 144

converted to base 6 = 104

converted to base 7 = 50

converted to base 8 = 36

converted to base 9 = 30

Here's my code:

`import java.util.*;`

public class Tester {

public static void main(String args[]) {

//ask user for number

Scanner k = new Scanner(System.in);

System.out.println("Please enter a positive integer.");

int input = k.nextInt();

System.out.println();

//this loop converts the number into each base from 2 to 9

//for each base the loop calls the convertNumber() method to do the conversion

for(int i=2; i<=9; i++) {

System.out.print("converted to base " + i + " = ");

convertNumber(input, i);

System.out.println();}

}

/*

* Recursive method that prints the given number in the given base

* example: if n = 13 and base = 2 (binary) then 1101 should be displayed

*/

private static void convertNumber(int n, int base) {

if (n >= base) {

n = n/base;

convertNumber(n, base);

int r = (n % base);

System.out.print(r);

}

} //end convertNumber

}//ends Tester

Answer

I see a bug in the convert number routine, if n is not GE than the base, you need an else, where you print out whatever n is. This is why all of your responses are missing the last digit.

Best of luck.

Source (Stackoverflow)