import java.io.*; public class DecimalToBinaryMain { public static void main (String[ ] args) { new DecimalToBinaryMain().readAndProcessInputs(); } // method main /** * Reads in non-negative integers (until sentinel of "-1" reached) and * prints out their binary equivalent. * */ public void readAndProcessInputs() { final String SENTINEL = "-1"; final String SENTINEL_MESSAGE = "\nThe sentinel is " + SENTINEL + ".\n"; final String PROMPT = "\nIn the Input line, please enter a non-negative base-10 integer: "; final String RESULT_MESSAGE = "The binary equivalent is "; BufferedReader reader = new BufferedReader (new InputStreamReader (System.in)); String line; System.out.println (SENTINEL_MESSAGE); while (true) { try { System.out.print (PROMPT); line = reader.readLine(); if (line.equals (SENTINEL)) break; System.out.println (RESULT_MESSAGE + getBinary (Integer.parseInt (line))); } // try catch (IOException e) { System.out.println (e); } // catch IOException catch (IllegalArgumentException e) { System.out.println (e); } // catch IllegalArgumentException } // while } // method readAndProcessInputs /** * * Determines the binary equivalent of a non-negative integer. The worstTime(n) * is O(log n), where n is the given integer. * * @param n the non-negative integer, in decimal notation. * * @return a String representation of the binary equivalent of n. * * @throws IllegalArgumentException if n is negative. */ public static String getBinary (int n) { if (n < 0) throw new IllegalArgumentException(); if (n <= 1) return Integer.toString (n); return getBinary (n / 2) + Integer.toString (n % 2); } // method getBinary } // class DecimalToBinaryMain