Guest User

Untitled

a guest
Nov 23rd, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. Scanner sc = new Scanner(System.in);
  2. boolean loop = false, restart = false;
  3. String input;
  4. int base;
  5. do{
  6. do{
  7. System.out.print("Enter base 10 value: ");
  8. input = sc.next();
  9. if(Integer.parseInt(input)<0){
  10. System.out.println("Invalid decimal number: "+input);
  11. loop = true;
  12. }else{
  13. loop=false;
  14. }
  15. }while(loop==true);
  16. do{
  17. System.out.print("Enter base to convert to: ");
  18. base = sc.nextInt();
  19. if(base>36){
  20. System.out.println("Invalid radix: "+base);
  21. loop = true;
  22. }else if(base<2){
  23. System.out.println("Invalid radix: "+base);
  24. loop = true;
  25. }else{
  26. loop = false;
  27. }
  28. }while(loop==true);
  29. String converted = convertBase(input,base);
  30. System.out.print(input+" in base "+base+" is "+converted);
  31. System.out.println();
  32. System.out.print("New Conversion? (y/n): ");
  33. if(sc.next().equals("y")){
  34. restart = true;
  35. }else{
  36. restart = false;
  37. }
  38. }while(restart == true);
  39.  
  40. public static String convertBase(String number, int targetBase){
  41. String converted = "";
  42. int temp = Integer.parseInt(number);
  43. int power = largestPower(temp, targetBase);
  44. int product[] = new int[power+1];
  45. int remain = temp;
  46. int j = 0;
  47. for(int i = power; i>=0;i--){
  48. product[j] =remain/( (int) Math.pow(targetBase, i));
  49. if(product[j]!=0){
  50. remain -= product[j]*Math.pow(targetBase, i);
  51. }
  52. j++;
  53. }
  54. char ascii;
  55. if(targetBase>=16){
  56. for(int k : product) {
  57. if(k>=10){
  58. k+=55;
  59. ascii = (char)k;
  60. converted+=ascii;
  61. }else{
  62. converted+=k;
  63. }
  64. }
  65. }else{
  66. for(int i : product) {
  67. converted+=i;
  68. }
  69. }
  70. return converted;
  71. }
  72.  
  73. public static int largestPower(int x, int target)
  74. {
  75. int power = 1;
  76. for (int i = target; i< x; i*=target){
  77. power++;
  78. }
  79. if(Math.pow(target, power)>x){
  80. power--;
  81. }
  82. return power;
  83. }
Add Comment
Please, Sign In to add comment