Examples of smaller Java programs that do various interesting things.

BinaryConverter.java 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. public class BinaryConverter {
  2. public static void main(String[] args){
  3. for(int i = -5; i < 33; i++){
  4. System.out.println(i + ": " + toBinary(i));
  5. System.out.println(i);
  6. //always another way
  7. System.out.println(i + ": " + Integer.toBinaryString(i));
  8. }
  9. }
  10. /*
  11. * pre: none
  12. * post: returns a String with base10Num in base 2
  13. */
  14. public static String toBinary(int base10Num){
  15. boolean isNeg = base10Num < 0;
  16. base10Num = Math.abs(base10Num);
  17. String result = "";
  18. while(base10Num > 1){
  19. result = (base10Num % 2) + result;
  20. base10Num /= 2;
  21. }
  22. assert base10Num == 0 || base10Num == 1 : "value is not <= 1: " + base10Num;
  23. result = base10Num + result;
  24. assert all0sAnd1s(result);
  25. if( isNeg )
  26. result = "-" + result;
  27. return result;
  28. }
  29. /*
  30. * pre: cal != null
  31. * post: return true if val consists only of characters 1 and 0, false otherwise
  32. */
  33. public static boolean all0sAnd1s(String val){
  34. assert val != null : "Failed precondition all0sAnd1s. parameter cannot be null";
  35. boolean all = true;
  36. int i = 0;
  37. char c;
  38. while(all && i < val.length()){
  39. c = val.charAt(i);
  40. all = c == '0' || c == '1';
  41. i++;
  42. }
  43. return all;
  44. }
  45. }