Advertisement
ArthurC

Untitled

Jan 16th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4. /**
  5. * Name:
  6. */
  7. public class ArrayPractice
  8. {
  9. public static void main(String[] args)
  10. {
  11. Scanner scanner = new Scanner(System.in);
  12. System.out.print("Enter the first number: ");
  13. int start = scanner.nextInt();
  14. int finish = start;
  15. while (finish <= start)
  16. {
  17. System.out.print("Enter the last number (must be after first number): ");
  18. finish = scanner.nextInt();
  19. }
  20.  
  21. // initialize an array to contain the numbers 'start' through 'finish', inclusive
  22. int[] numbers = buildArray(start, finish);
  23.  
  24. // print the message passed in, then all the numbers in the array
  25. System.out.printf(Arrays.toString(numbers));
  26.  
  27.  
  28. // print the sum and average of the numbers
  29. printSumAndAverage(numbers);
  30.  
  31. // Bonus:
  32. // add 1 to all odd numbers
  33. addOneToOddNumbers(numbers);
  34. System.out.printf(Arrays.toString(numbers));
  35. reverse(numbers);
  36. System.out.println("");
  37. System.out.printf(Arrays.toString(numbers));
  38.  
  39. }
  40. public static int[] buildArray(int start, int finish)
  41. {
  42. int lengte=(finish-start)+1;
  43. int array[]=new int[lengte];
  44. int teller=0;
  45. for (int i=start;i<finish+1;i++)
  46. {
  47. array[teller]=i;
  48. ++teller;
  49. }
  50. return array;
  51. }
  52.  
  53.  
  54.  
  55. /**
  56. * Method that prints the SUM and the AVERAGE of the numbers in the array
  57. */
  58. public static void printSumAndAverage(int[] array)
  59. {
  60. int som=0;
  61. int gemiddelde=0;
  62.  
  63. for(int i=0; i<array.length;i++)
  64. {
  65. som += array[i];
  66. }
  67. gemiddelde = som/array.length;
  68.  
  69. System.out.printf("%nDe som is %s%nHet gemiddelde is %s%n",som,gemiddelde);
  70. }
  71.  
  72. // Start with this main() method. Do not change it!
  73.  
  74. public static void addOneToOddNumbers(int[]array)
  75. {
  76. for (int i=0; i<array.length;i++)
  77. {
  78. if(array[i]%2==0)
  79. {++array[i];}
  80. }
  81.  
  82. }
  83.  
  84. public static void reverse (int[]arr)
  85. { int temp=0;
  86. int l = arr.length-1;
  87. for(int i=0;i<l/2;i++)
  88. {
  89. temp=arr[l];
  90. arr[l]=arr[i];
  91. arr[i]=temp;
  92. l--;
  93. }
  94. }
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement