Examples of smaller Java programs that do various interesting things.

EnhancedFor.java 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. public class EnhancedFor
  2. {
  3. public static void main(String[] args)
  4. { int[] list ={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  5. int sum = sumListEnhanced(list);
  6. System.out.println("Sum of elements in list: " + sum);
  7. System.out.println("Original List");
  8. printList(list);
  9. System.out.println("Calling addOne");
  10. addOne(list);
  11. System.out.println("List after call to addOne");
  12. printList(list);
  13. System.out.println("Calling addOneError");
  14. addOneError(list);
  15. System.out.println("List after call to addOneError. Note elements of list did not change.");
  16. printList(list);
  17. }
  18. // pre: list != null
  19. // post: return sum of elements
  20. // uses enhanced for loop
  21. public static int sumListEnhanced(int[] list)
  22. { int total = 0;
  23. for(int val : list)
  24. { total += val;
  25. }
  26. return total;
  27. }
  28. // pre: list != null
  29. // post: return sum of elements
  30. // use traditional for loop
  31. public static int sumListOld(int[] list)
  32. { int total = 0;
  33. for(int i = 0; i < list.length; i++)
  34. { total += list[i];
  35. System.out.println( list[i] );
  36. }
  37. return total;
  38. }
  39. // pre: list != null
  40. // post: none.
  41. // The code appears to add one to every element in the list, but does not
  42. public static void addOneError(int[] list)
  43. { for(int val : list)
  44. { val = val + 1;
  45. }
  46. }
  47. // pre: list != null
  48. // post: adds one to every element of list
  49. public static void addOne(int[] list)
  50. { for(int i = 0; i < list.length; i++)
  51. { list[i]++;
  52. }
  53. }
  54. public static void printList(int[] list)
  55. { System.out.println("index, value");
  56. for(int i = 0; i < list.length; i++)
  57. { System.out.println(i + ", " + list[i]);
  58. }
  59. }
  60. }