AliceBobCatherineDough
AliceBobCatherineDough

Reputation: 105

Convert a base 10 number to a base 3 number

How to convert a base 10 number to a base 3 number with a method int converter(int num).

import java.util.Scanner;

public class BaseConverter {
    int answer;
    int cvt = 0;
    while (num >= 0) {
        int i = num / 3;
        int j = num % 3;
        String strj = Integer.toString(j);
        String strcvt = Integer.toString(cvt);
        strcvt = strj + strcvt;
        num = i;
        break;
    }
    answer = Integer.parseInt("strcvt");
    return answer;
}

public static void main(String[] agrs) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter a number: ");
    int number = in.nextInt();
    System.out.print(converter(number));
    in.close();
}

It was Compilation completed. But when I tried to run it, and entered a number, it showed that java.lang.NumberFormatException: For input string: "strcvt" I don't know how to fix it. How can I do this without using string?

Upvotes: 9

Views: 11058

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533790

You shouldn't need to use String at all.

Try this instead

public static long asBase3(int num) {
    long ret = 0, factor = 1;
    while (num > 0) {
        ret += num % 3 * factor;
        num /= 3;
        factor *= 10;
    }
    return ret;
}

Note: numbers in the computer are only ever N-bit i.e. 32-bit or 64-bit i.e. they are binary. However, what you can do is create a number that when printed at base 10, will actually appear to be the number in base 3.

Upvotes: 7

Sergey Fedorov
Sergey Fedorov

Reputation: 2169

"base 3 number" and "base 10 number" are the same number. In method int converter(int num) you're changing the number although you only need to change representation. Look at parseInt(String s, int radix) and toString(int i, int radix), that should help you.

Upvotes: 5

Jens
Jens

Reputation: 69470

You have to parse the value of strcvt not the string "strcvt"

So you have to remove the double qoutes answer = Integer.parseInt(strcvt); And define the variable strcvt outside the loop. change you code to:

public static int converter(int num) {
    int answer;
    int cvt = 0;
    String strcvt = null ;
    while (num >= 0) {
        int i = num / 3;
        int j = num % 3;
        String strj = Integer.toString(j);
        strcvt = Integer.toString(cvt);
        strcvt = strj + strcvt;
        num = i;
        break;
    }
    answer = Integer.parseInt(strcvt);
    return answer;
}

Upvotes: 2

Ankur Singhal
Ankur Singhal

Reputation: 26077

you are not using variable declared String strcvt, instead due to typo mistake you have used as "strcvt"

change

answer = Integer.parseInt("strcvt");

to

answer = Integer.parseInt(strcvt);

Upvotes: 3

Related Questions