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?
The base 3, or ternary, system, uses only the digits 0,1, and 2. For each place, instead of multiplying by the power of 10, you multiply by the power of 3. For example, 120123→1×34+2×33+0×32+1×31+2.
Steps to Convert Decimal to Ternary:Divide the number by 3. Get the integer quotient for the next iteration. Get the remainder for the ternary digit. Repeat the steps until the quotient is equal to 0.
To convert any number in (our base) Base 10 to any other base, we must use basic division with remainders. Do not divide using decimals; the algorithm will not work. Keep dividing by 5, until your quotient is zero. Now write your remainders backwards!
"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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With