package types; import java.util.Scanner; public class IO { private static Scanner scanner = new Scanner (System.in); private static final String zeros32 = "00000000000000000000000000000000"; private static final String zeros = zeros32 + zeros32; public static int promptForInt (String name) { System.out.print ("int " + name + ">"); return scanner.nextInt (); } public static byte promptForByte (String name) { System.out.print ("byte " + name + ">"); return scanner.nextByte (); } public static short promptForShort (String name) { System.out.print ("short " + name + ">"); return scanner.nextShort (); } public static long promptForLong (String name) { System.out.print ("long " + name + ">"); return scanner.nextLong (); } public static float promptForFloat (String name) { System.out.print ("float " + name + ">"); return scanner.nextFloat (); } public static double promptForDouble (String name) { System.out.print ("double " + name + ">"); return scanner.nextDouble (); } public static boolean promptForBoolean (String name) { System.out.print ("boolean " + name + ">"); return scanner.nextBoolean (); } public static void writeResult (String text, Object value) { System.out.println (text + "=" + value); } public static void writeBinary (String text1, Object value1, String text2, Object value2, String text3, Object value3) { writeBinary (text1, value1); writeBinary (text2, value2); writeBinary (text3, value3); } public static void writeBinary (String text1, Object value1, String text2, Object value2) { writeBinary (text1, value1); writeBinary (text2, value2); } public static void writeBinary (String text, Object value) { String binary = null; if (value instanceof Byte) { binary = format (Long.toBinaryString ((Byte) value), 8); } else if (value instanceof Short) { binary = format (Integer.toBinaryString ((Short) value), 16); } else if (value instanceof Integer) { binary = format (Integer.toBinaryString ((Integer) value), 32); } else if (value instanceof Long) { binary = format (Long.toBinaryString ((Long) value), 64); } else if (value instanceof Float) { binary = Integer.toBinaryString (Float.floatToIntBits (((Float) value))); binary = format (binary, 32, 1, 9); } else if (value instanceof Double) { binary = Long.toBinaryString (Double.doubleToLongBits (((Double) value))); binary = format (binary, 64, 1, 12); } else if (value instanceof java.lang.Boolean) { binary = value + " "; } else { binary = value + " isn't a primitive type; it's a " + value.getClass (); } System.out.println (text + " = " + binary); } private static String format (String binary, int digits) { return zeros.substring (0, Math.max (0, digits - binary.length ())) + binary; } private static String format (String binary, int digits, int splitAt1, int splitAt2) { binary = format (binary, digits); return binary.substring (0, splitAt1) + " " + binary.substring (splitAt1, splitAt2) + " " + binary.substring (splitAt2, digits); } }