Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class CoveringBases {
- private String originalNumber;
- private String newNumber;
- private int originalBase = 10;
- private int newBase;
- public CoveringBases() {
- this.askUser();
- this.checkValidity();
- this.printAll();
- }
- private void askUser() {
- Scanner input = new Scanner(System.in);
- System.out.print("Enter the number base 10 to convert: ");
- originalNumber = input.nextLine();
- System.out.print("Enter the new base: ");
- newBase = input.nextInt();
- }
- private void checkValidity() {
- if (newBase < 2 || 16 < newBase) {
- System.out.println("Not an acceptable base.");
- System.exit(0);
- }
- }
- private void printAll() {
- System.out.print("The number " + originalNumber + " [base 10] = ");
- System.out.print(convertNumber() + " [base " + newBase + "]");
- }
- private String convertNumber() {
- double value = 0;
- double decDigit = 0;
- char chDigit = 0;
- int length = originalNumber.length();
- // loop through each digit of the original number
- for (int power = 0; power < length; power++) {
- // get the digit character (0 - 9, A - Z)
- chDigit = Character.toUpperCase(originalNumber.charAt(length - 1 - power));
- // get the decimal value of the character
- if (Character.isLetter(chDigit)) {
- decDigit = chDigit - 'A' + 10;
- }
- else if (Character.isDigit(chDigit)) {
- decDigit = chDigit - '0';
- }
- else {
- System.out.println("Not a recognized digit.");
- System.exit(1);
- }
- // add this digit's value to the total
- value += decDigit * Math.pow(originalBase, power);
- }
- int D = 1;
- for (; Math.pow(newBase, D) <= value; D++) {
- }
- // use char array to hold the new digits
- char[] newNum = new char[D];
- double pwr;
- for (int i = D - 1; i >= 0; i--) {
- // calculate the digit for this power of newBase
- pwr = Math.pow(newBase, i);
- decDigit = Math.floor(value / pwr);
- value -= decDigit * pwr;
- // store the digit character
- if (decDigit <= 9) {
- newNum[D - 1 - i] = (char) ('0' + (int) decDigit);
- }
- else {
- newNum[D - 1 - i] = (char) ('A' + (int) (decDigit - 10));
- }
- }
- return new String(newNum);
- }
- public static void main(String[] args) {
- new CoveringBases();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement