In Java, write this program. This Ternary Base 3 program takes a positive intege
ID: 3879194 • Letter: I
Question
In Java, write this program.
This Ternary Base 3 program takes a positive integer that is inputted from the user and converted into ternary base 3. Write a decimal to a ternary converter. Assume the user enters a positive integer no bigger than 666. Read it and display the base-3 equivalent. (It will be helpful in the next program if you have somehow saved the digits, rather than simply calculating and printing them.)
this is what I got so far. I'm not sure if it is in the right direction or not.
import java.util.Scanner;
public class Ternary_Based {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int TernaryAnswer = 0;
int input;
System.out.println("Enter input: ");
input = sc.nextInt();
sc.close();
while (input > 0) {
int factor = 1;
TernaryAnswer += input % 3 * factor;
input /= 3;
factor *= 10;
}
System.out.println(TernaryAnswer);
}
}
0 0 1 1 2 2 3 10 27 1000Explanation / Answer
import java.util.*;
import java.io.*;
public class Ternary_Based {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int TernaryAnswer = 0;
int input;
System.out.println("Enter input: ");
input = sc.nextInt();
sc.close();
int factor = 1;
while (input > 0) {
TernaryAnswer += input % 3 * factor;
input /= 3;
factor *= 10;
}
System.out.println(TernaryAnswer);
}
}
This would be the proper program. the mistake was that you initialized the factor variable inside the loop
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.