Advertisement
Guest User

Untitled

a guest
May 29th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.20 KB | None | 0 0
  1.  
  2. import java.util.Scanner;
  3.  
  4. /*
  5. * To change this license header, choose License Headers in Project Properties.
  6. * To change this template file, choose Tools | Templates
  7. * and open the template in the editor.
  8. */
  9.  
  10. /**
  11. *
  12. * @author SHON
  13. */
  14. public class Main {
  15.  
  16. /**
  17. * @param args the command line arguments
  18. */
  19. public static void main(String[] args) {
  20. System.out.println("To finish, please type 'n'");
  21. System.out.println("Plese input a mark.");
  22.  
  23. Scanner s = new Scanner(System.in);
  24. while (true)
  25. {
  26. avergaeCalculation();
  27.  
  28. System.out.println("Do you wish to continue? (y/n)");
  29.  
  30. String str = s.next();
  31. if (str != null && str != "y")
  32. {
  33. break;
  34. }
  35. }
  36.  
  37.  
  38.  
  39. //Console.ReadLine();
  40. }
  41.  
  42. private static void avergaeCalculation()
  43. {
  44. Scanner s = new Scanner(System.in);
  45.  
  46. int[] arr = {};
  47.  
  48. while (true)
  49. {
  50. // Ask user for the number
  51.  
  52. String str = s.next();
  53. if (str != null && "n".equals(str))
  54. {
  55. break;
  56. }
  57. /**/
  58. int mark = 0 ;//= s.nextInt();
  59.  
  60.  
  61. // Make sure that the mark is a number
  62.  
  63.  
  64. while (true)
  65. {
  66. try
  67. {
  68. mark = Integer.parseInt(str);
  69. break;
  70. }
  71. catch(NumberFormatException e)
  72. {
  73. System.out.println("Your input is invalid! Please enter a mark.");
  74. str = s.next();
  75. }
  76. }
  77.  
  78.  
  79. // Accumlate the marks
  80.  
  81. // Add
  82.  
  83.  
  84.  
  85. arr = addMark(arr, mark);
  86.  
  87. // Ask the user if they want to continue
  88. }
  89.  
  90. // Divide the count and accumulated marks
  91. int count = arr.length;
  92.  
  93. int markSum = 0;
  94.  
  95. for(int i = 0; i < arr.length; i++)
  96. {
  97. markSum += arr[i];
  98. }
  99.  
  100. double average = count > 0 ? (double)markSum / count : 0.0;
  101.  
  102. System.out.println(String.format("Your average mark is: %1$,.2f", average));
  103. }
  104.  
  105. private static int[] addMark(int[] arr, int mark)
  106. {
  107. int[] temp = arr != null ? new int[arr.length + 1] : new int[1];
  108.  
  109. Copy(arr, temp);
  110.  
  111. temp[temp.length - 1] = mark;
  112.  
  113. return temp;
  114. }
  115.  
  116. private static void Copy(int[] source, int[] target)
  117. {
  118. if (source == null || target == null)
  119. {
  120. return;
  121. }
  122.  
  123. for (int i = 0; i < source.length && i < target.length; i++)
  124. {
  125. target[i] = source[i];
  126. }
  127. }
  128.  
  129. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement