Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- /**
- *
- * @author SHON
- */
- public class Main {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- System.out.println("To finish, please type 'n'");
- System.out.println("Plese input a mark.");
- Scanner s = new Scanner(System.in);
- while (true)
- {
- avergaeCalculation();
- System.out.println("Do you wish to continue? (y/n)");
- String str = s.next();
- if (str != null && str != "y")
- {
- break;
- }
- }
- //Console.ReadLine();
- }
- private static void avergaeCalculation()
- {
- Scanner s = new Scanner(System.in);
- int[] arr = {};
- while (true)
- {
- // Ask user for the number
- String str = s.next();
- if (str != null && "n".equals(str))
- {
- break;
- }
- /**/
- int mark = 0 ;//= s.nextInt();
- // Make sure that the mark is a number
- while (true)
- {
- try
- {
- mark = Integer.parseInt(str);
- break;
- }
- catch(NumberFormatException e)
- {
- System.out.println("Your input is invalid! Please enter a mark.");
- str = s.next();
- }
- }
- // Accumlate the marks
- // Add
- arr = addMark(arr, mark);
- // Ask the user if they want to continue
- }
- // Divide the count and accumulated marks
- int count = arr.length;
- int markSum = 0;
- for(int i = 0; i < arr.length; i++)
- {
- markSum += arr[i];
- }
- double average = count > 0 ? (double)markSum / count : 0.0;
- System.out.println(String.format("Your average mark is: %1$,.2f", average));
- }
- private static int[] addMark(int[] arr, int mark)
- {
- int[] temp = arr != null ? new int[arr.length + 1] : new int[1];
- Copy(arr, temp);
- temp[temp.length - 1] = mark;
- return temp;
- }
- private static void Copy(int[] source, int[] target)
- {
- if (source == null || target == null)
- {
- return;
- }
- for (int i = 0; i < source.length && i < target.length; i++)
- {
- target[i] = source[i];
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement