Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Scanner sc = new Scanner(System.in);
- boolean loop = false, restart = false;
- String input;
- int base;
- do{
- do{
- System.out.print("Enter base 10 value: ");
- input = sc.next();
- if(Integer.parseInt(input)<0){
- System.out.println("Invalid decimal number: "+input);
- loop = true;
- }else{
- loop=false;
- }
- }while(loop==true);
- do{
- System.out.print("Enter base to convert to: ");
- base = sc.nextInt();
- if(base>36){
- System.out.println("Invalid radix: "+base);
- loop = true;
- }else if(base<2){
- System.out.println("Invalid radix: "+base);
- loop = true;
- }else{
- loop = false;
- }
- }while(loop==true);
- String converted = convertBase(input,base);
- System.out.print(input+" in base "+base+" is "+converted);
- System.out.println();
- System.out.print("New Conversion? (y/n): ");
- if(sc.next().equals("y")){
- restart = true;
- }else{
- restart = false;
- }
- }while(restart == true);
- public static String convertBase(String number, int targetBase){
- String converted = "";
- int temp = Integer.parseInt(number);
- int power = largestPower(temp, targetBase);
- int product[] = new int[power+1];
- int remain = temp;
- int j = 0;
- for(int i = power; i>=0;i--){
- product[j] =remain/( (int) Math.pow(targetBase, i));
- if(product[j]!=0){
- remain -= product[j]*Math.pow(targetBase, i);
- }
- j++;
- }
- char ascii;
- if(targetBase>=16){
- for(int k : product) {
- if(k>=10){
- k+=55;
- ascii = (char)k;
- converted+=ascii;
- }else{
- converted+=k;
- }
- }
- }else{
- for(int i : product) {
- converted+=i;
- }
- }
- return converted;
- }
- public static int largestPower(int x, int target)
- {
- int power = 1;
- for (int i = target; i< x; i*=target){
- power++;
- }
- if(Math.pow(target, power)>x){
- power--;
- }
- return power;
- }
Add Comment
Please, Sign In to add comment