Lab Description:
Lab # 3 is call Classes and Methods. The goal of this lab is to break down the program (in lab # 2) into classes. So in a other word, break all the if/while loop, in lab # 2 into methods/fields. One of the idea in the lab is to use overloading. But I didn’t use overloading because it was a lot harder to use then I image, so overloading wasn’t use in this program. The first thing is too create and program title: NumberStats that will have all the steps in lab 2 here. Example: First, Last, Count of number, Max, Min, Sum, and Average. The NumberStats need to be able to compute all these statistics this like lab 2. Use get.methods for the first part of the lab. The next stop is to create a program call TrainStats. Here is the meat of this lab. This program need to call NumberStats to compute all the statistics. So in other word TrainStats will instantiate NumberStats and it will compute all the statistics.
Code:
Part 1:
public class NumberStats { private double first; private double last ; private double minimum= 898934943; private double maximum; private double average; private double total; private int count; private double sum; public NumberStats(){ this.count = 0; this.sum = 0; } public void setNewNumber(double newNumber){ count++; sum += newNumber; average = sum/count; if(count == 1){ maximum = newNumber; first = newNumber; } if(newNumber 0){ last = newNumber; } if(newNumber > maximum){ maximum = newNumber; } total = newNumber + sum; } public double getFirst(){ return first; } public double getLast(){ return last; } public double getMinimum(){ return minimum; } public double getMaximum(){ return maximum; } public double getAverage(){ return average; } public int getCount(){ return count; } public double getTotal() { return total; } }
import java.util.Scanner; public class TrainStats { /** * @param args */ public static void main(String[] args) { System.out.print("Enter any amount of numbers: "+"\n"); System.out.println("press 0 to exit"); NumberStats myNumber = new NumberStats(); double newNumber = 0.0; while(true) { Scanner input = new Scanner(System.in); newNumber = input.nextDouble(); if (newNumber== 0) break; myNumber.setNewNumber(newNumber); } System.out.println("First: " + myNumber.getFirst()); System.out.println("Last: " + myNumber.getLast()); System.out.println("Minimum: " + myNumber.getMinimum()); System.out.println("Maximum: " + myNumber.getMaximum()); System.out.println("Average: " + myNumber.getAverage()); System.out.println("Total Sum: " + myNumber.getTotal()); System.out.println("Count of number entered:" + myNumber.getCount()); } }