Advertisement
brilliant_moves

Dec2Any.java

Sep 7th, 2012
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.84 KB | None | 0 0
  1. public class Dec2Any {
  2.  
  3.     /*
  4.     *   Program:    Dec2Any.java
  5.     *   Purpose:    Convert decimal to any lower base
  6.     *   Creator:    Chris Clarke
  7.     *   Created:    04.04.2012
  8.     */
  9.  
  10.     public static void main(String[] args) {
  11.         if (args.length == 2) {
  12.             int decimal = Integer.parseInt(args[0]);
  13.             if (decimal < 0) {
  14.                 System.out.println("Error: number out of range");
  15.                 System.exit(0);
  16.             }
  17.  
  18.             int base = Integer.parseInt(args[1]);
  19.             if (base < 2 || base > 10) {
  20.                 System.out.println("Error: base out of range");
  21.                 System.exit(0);
  22.             }
  23.  
  24.             System.out.println( toBase(decimal, base));
  25.         } else {
  26.             System.out.println("Use: \"java Dec2Any <decimal number> <base>\"");
  27.         }
  28.     }
  29.  
  30.     static String toBase(int num, int base) {
  31.         String result = "";
  32.         do {
  33.             result = (num % base) + result;
  34.             num = num / base;
  35.         } while (num > 0);
  36.         return result;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement