Get an average from number of objects - java

I'm trying to get the average score from objects but can't think of a good way to do it.
I have 10 objects and they all have their own score associated with it.
I created setter and getter class where it would get the average, but the problem I run into is that I would create something like this so that even if I do put object's score into this method the holder will go back to 0.
public double getAverage() {
return average;
}
public void setAverage(double studentScore) {
double holder = 0;
average = holder + studentScore;
holder = average;
this.average = studentScore;
}
I was also thinking of just creating setter and getter methods for every single score, but that takes up lots of space and I figured there has to be a better way to do it.
Here is a snippet of the code I'm using in the main method
public static void main(String[] args) {
final String STUDENT_INFO = "HW1_Students.txt";
List<GradeInfo> list = new ArrayList<GradeInfo>();
Scanner inputFile = null;
GradeInfo person1 = new GradeInfo();
GradeInfo person2 = new GradeInfo();
GradeInfo person3 = new GradeInfo();
GradeInfo person4 = new GradeInfo();
GradeInfo person5 = new GradeInfo();
GradeInfo person6 = new GradeInfo();
GradeInfo person7 = new GradeInfo();
GradeInfo person8 = new GradeInfo();
GradeInfo person9 = new GradeInfo();
GradeInfo person10 = new GradeInfo();
list.add(person1);
list.add(person2);
list.add(person3);
list.add(person4);
list.add(person5);
list.add(person6);
list.add(person7);
list.add(person8);
list.add(person9);
list.add(person10);
try {
inputFile = new Scanner(new File(STUDENT_INFO));
}
catch (FileNotFoundException ex) {
System.out.println("\n *** Exception occured while opening "
+ ex.getMessage() + " ***");
System.exit(-1);
}
readData(inputFile, STUDENT_INFO, person1, person2, person3, person4,
person5, person6, person7, person8, person9, person10);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
Any advice would be greatly appreciated, thanks.

public void setAverage(ArrayList<GradeInfo> grades) {
double average = 0;
for(int i = 0; i < grades.size(); i++){
average += grades.get(i);
}
average = average / grades.size();
this.average = average;
}
I hope this is what you meant to do....... This method will take your Arraylist, and set the correct average score in your wired "setter and getter class".

I dont really understand what you are trying to do here:
public void setAverage(double studentScore) {
double holder = 0;
average = holder + studentScore;
holder = average;
this.average = studentScore;
}
But its logical that holder will be reset to 0 because you initialize it and set it to 0 in the beginnig of your function, or do i misunderstand this?
Just create holder outside of your setter.
And if you just want to have the average of a bunch of values just add all the values together and divide the result by the number/quantity of your values.
For example:
public double getAverage(List <GradeInfo> l){
int totalAmount;
for(i = 0; i < l.size(); i++){
totalAmount += l.get(i);
}
double average = totalAmount / l.size();
return average;
}

This is probably not applicable to your program insofar as you probably have at least one positive value going into your calculation. But I could see a professor taking off points for it if he is testing all possible cases.
If you do follow the advice of Sand, be sure to check that the size of the arraylist is greater than zero before you use the size in the average calculation. You cannot divide by zero in Java. Instead, do this:
public double getAverage(List <GradeInfo> l){
int totalAmount;
for(i = 0; i < l.size(); i++){
totalAmount += l.get(i);
}
if (l.size() > 0) {
double average = totalAmount / l.size();
return average;
else {
double average = 0;
}
return average;
}

Related

why is my program asking for output twice

Scanner sam = new Scanner(System.in);
public class balance {
public double[] returnarray1() {
System.out.print("Enter account balances seperated by coma:");
String[] temp = sam.nextLine().split(",");
double[] bal = new double[temp.length];
for(int i=0; i<temp.length; i++) {
bal[i] = Double.parseDouble(temp[i]);
}
return bal;
}
}
public class interest {
public double[] returnarray2() {
balance bl = new balance();
double[] temp = bl.returnarray1();
double[] inter = new double[temp.length];
for(int i=0;i>temp.length;i++) {
inter[i] = temp[i] * 0.02/12;
}
return inter;
}
}
public static void main(String[] args) {
samiksood ss = new samiksood();
balance bl = ss.new balance();
interest it = ss.new interest();
double[] balance = bl.returnarray1();
double[] interest = it.returnarray2();
for(int i =0; i<balance.length;i++) {
System.out.print("Account "+ i +1);
System.out.print(balance[i]);
System.out.println(interest[i]);
}
}
when i run it it asks me for output twice which should not happen why is my class repeating?
this program is supposed to seperate a single output into multiple different ones and be placed into a array which is then converted to double the balance is then returned. similarly interest is calculated by preforming calculations on each balance array and returned.they are called into the main method and each array is supposed to be printed.
You both call returnarray1 in your main and inside returnarray2 so that's why returnarray1 is executed twice.
Assuming you want to use the result of the first time in the second time you can change
public double[] returnarray2() {
balance bl = new balance();
double[] temp = bl.returnarray1();
double[] inter = new double[temp.length];
for (int i = 0; i > temp.length; i++) {
inter[i] = temp[i] * 0.02 / 12;
}
return inter;
}
to
public double[] returnarray2(double[] temp) {
balance bl = new balance();
double[] inter = new double[temp.length];
for (int i = 0; i > temp.length; i++) {
inter[i] = temp[i] * 0.02 / 12;
}
return inter;
}
and
double[] interest = it.returnarray2();
to
double[] interest = it.returnarray2(balance);
I believe there is also a small bug at this line
for (int i = 0; i > temp.length; i++) {
because it needs to be
for (int i = 0; i < temp.length; i++) {
There's a lot more room for improvement, because a lot of your code is not according to conventions, but it should work at least.

Run a method in a loop to get Max, Min from an Array List

Background: The method name is computeStatsMean(). It takes the initial value of 100 and adds a weekly profit to it by randomly sampling the mean weekly profit from a normal distribution. It needs to calculate how much a value of 100 would turn into, in 3582 weeks. I have to run 1000 trials of that method to see how different values of mean weekly profit values from normal distribution gets us the different values of profit. I have to store the 1000 equity return (profit values or "new values") in an ArrayList and get Maximum, Minimum, Median from it.
Problem: I'm able to run method and do sampling and all. But i'm unable to run it for 1000 trials. I tried calling the method in the main 1000 times (1000 for loop) but it replaced the old value with the new one in the ArrayList.
Code:
class Sample extends SimulateMarket{
public ArrayList<Double> data = new ArrayList<Double>();
public ArrayList<Double> myData = new ArrayList<Double>();
private double mean, stdDev;
private Random random;
private SimulateMarket mySim = new SimulateMarket(); //mySim is an instance of SimulateMarket class used to access variables of Simulate Class
//Constructor
public Sample(){ //Constructor used for the Distributional Technique
random = new Random();
int size = 3582;
for(int i=0; i<size ; i++)
data.add(0.0016+random.nextGaussian()*0.0205); //Random sampling from Normal Distribution
System.out.println(this); //for printing the results
}
//Getters (Mean, Standard Deviation, Median)
public double getMean(){
double sum=0;
for(int i=0; i<mySim.WEEK; i++)
sum += data.get(i);
return sum/data.size();
}
public void computeStatsMean(){
double equity = 100;
for(int i=0; i<100; i++){
equity = equity*(1+getMean());
}
myData.add(equity);
System.out.println("mean : " + getMean());
for(Double num: myData){
System.out.println("with mean:" + num);
}
}
class SimulateMarket{
public static void main(String[] args){
for(int i=0; i<1000; i++){
Sample equity = new Sample();
equity.computeStatsMean();
}
}
}
You are creating new instance of Sample every time inside for-loop in main().
Sample equity = new Sample();
Hence when invoking equity.computeStatsMean(); old values are lost.
Try like below:
Sample equity;
public static void main(String[] args) {
equity = new Sample();
for(int i = 0; i < 1000; i++) {
equity.computeStatsMean();
}
}
In computeStatsMean() change:
equity = equity*(1+getMean());
to
equity = equity*(i+getMean()); // use i instead of 1
In computeStatsMean(), start the counter value from 1 instead of 0. (Hope you can figure out why!)
I placed the computeStatsMean() renamed it to Distributional method in the SimulateMarket class and used the Sample class to hold the values. It's working now.
class SimulateMarket{ //Application Class (it contains the Main Method)
//public instance variables
public double meanWeekly = 0.0016; //Average weekly return
public double median = 0.0029; //the middle value is known as Median
public final int WEEK = 3582; //Data calculate over the course of 3582 weeks
public final int WEEK_YEAR = 52; //The number can never changes; hence, "final."
//private instance variables
private double meanYearly = meanWeekly * WEEK_YEAR; //Formula for average yearly return
private double stdDev = 0.0205;
public double Distributional(){
Sample mySampleA = new Sample();
double equity = 100;
for(int i=0; i<3582; i++){
equity = equity*(1+mySampleA.getMean());
}
return equity;
}
public static void main(String[] args){
Sample b = new Sample();
b.computeStats();
}
}
class Sample{
public void computeStats(){
for(int i=0; i<4; i++){
myDataA.add(super.Distributional());
}
for(Double num: myDataA){
System.out.println(num);
}
System.out.println(toStringA());
}
public String toStringA(){
return String.format("\nDistrubution: size = %d, mean = %.2f, stdDev = %.2f, min = %.2f, max = %.2f, median = %.2f", myDataA.size(), getMeanA(), getStdDevA(mean), Collections.min(myDataA), Collections.max(myDataA), getMedianA());
}
}

Code for adding doubles within a text file? Java

I was wondering if the following code returns a sum of all the doubles in a text file. It seems to always appear as 0.0 when I test run it. What could be the problem? I
public double honorsCalculation() throws IOException {
Scanner test = new Scanner(new File("Calculus - Test.txt"));
while (test.hasNext()) {
ArrayList <Double> assignments = new ArrayList <Double> ();
double num = test.nextDouble();
assignments.add(num);
for (int i = 1; i < assignments.size() - 1; i++) {
sum = sum + assignments.get(i);
percentage = sum;
}
}
return percentage;
}
You don't need the ArrayList at all, and it's hard to see how a percentage can be equal to a sum, or where your variables are being initialized:
public double honorsCalculation() throws IOException {
double sum = 0;
Scanner test = new Scanner(new File("Calculus - Test.txt"));
while (test.hasNext()) {
sum += test.nextDouble();
}
return sum;
}
You are treating the information before reading all the data.
public double honorsCalculation() throws IOException {
Scanner test = new Scanner(new File("Calculus - Test.txt"));
ArrayList <Double> assignments = new ArrayList <Double> ();
while (test.hasNext()) {
double num = test.nextDouble();
assignments.add(num);
}
for (int i = 1; i < assignments.size() - 1; i++) {
sum = sum + assignments.get(i);
percentage = sum;
}
return percentage;
}
This should be the correct approach.

Java finding place in an array?

So I have to find the minimum in an array in Java, but with that I have to print out the corresponding names that go with the minimum in another parallel array. Inside my for loop where I find the minimum, I have a variable place that I set equal to my counter variable from the for loop when the minimum is changed. But every time I print out the name, it prints out the first name in the array instead of the name in the place holder.
public double getMinimum(double[] money)
{
double lowest = money[0];
for (int p = 0; p < money.length; p++)
{
if (money[p] < lowest)
{
lowest = money[p];
place = p;
}
}
return lowest;
}
Theres the for loop within my programmer-defined class that finds the minimum.
public String getFirstNameMin(String[] firstName)
{
String minFirstName;
minFirstName = firstName[place];
return minFirstName;
}
This is the code I'm using to figure out the first name from the first names array at that place. What am I doing wrong? I'm kinda new to Java, but I did all this array stuff in C++ before, so idk if I am missing something very simple, or its different in Java.
I would say try making a separate class for this that contains the user and the money:
public class User {
private double money;
private String fname;
private String lname;
//getters/setters/constructors
}
Then from there you can simply compare the accounts:
public User getMinimum(User[] users) {
if (users.length <= 0) {
return null;
}
User lowest = users[0];
for (int i = 1; i < users.length; i++) {
if (users[i].getMoney() < lowest.getMoney()) {
lowest = users[i];
}
}
return lowest;
}
Try this:
public int getMinIndex(double[] money)
{
double min = money[0];
int minIndex = 0;
for (int p = 0; p < money.length; p++)
{
if (money[p] < min)
{
min = money[p];
minIndex = p;
}
}
return minIndex;
}
public static void main(String[] args)
{
double[] money;
String[] name;
//... init your arrays here!
int index = getMinIndex(money);
System.out.println("Min money = " + money[index] + "; name = " + name[index]);
}
However, following an object oriented approach rogues solution is much nicer!!!

converting single dimensional array into multidimensional array

I'm trying to convert my single dimensional array into a multidimensional array. Convert the existing Interest Calculator Batch application from several single dimensional arrays
into 1 multi-dimensional array. Use the following data type: double[][] values;
Hint: The maximum number of data sets(5) will be your row and the each data array (from the original InterestCalculatorBatch)(7)will be a column.
2.All data will be contained within a
single multi-dimensional array.
3. Modify the sortBySimple and displayInterest methods to accept a single multi-dimensional array instead of multiple single dimensional arrays
I fixed the displayInterest to accept a single multi dimensional array. I am just confused if I have the sortBySimple set up correctly and when the program calculates the interest if I need to fix those or keep them as is. Thank you for the help.
import java.util.Scanner;
public class InterestCalculatorBatchMDA {
public static void main(String[] args )
{
int cnt = 0;
double[][] arrPrincipalAmt = new double[5][7];
double[][] arrInterestRate = new double[5][7];
double[][] arrTerm = new double[5][7];
double[][] arrSimple = new double[5][7];
double[][] arrCompoundMonthly = new double[5][7];
double[][] arrCompoundDaily = new double[5][7];
double[][] arrCompoundWeekly = new double[5][7];
do{
arrPrincipalAmt[cnt] = getPrincipalAmount(1);
arrInterestRate[cnt] = getInterestRate(1);
arrTerm[cnt] = getTerm(1);
arrSimple[cnt] = round(calculateSimpleInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt]),5);
arrCompoundMonthly[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt],arrTerm[cnt] ,12.0 ),5);
arrCompoundWeekly[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt], 52.0 ),5);
arrCompoundDaily[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt], 365.0 ),5);
cnt++;
}while (cnt < 5 && askYesNo("Enter another set of data (Yes/No):"));
displayInterest(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
sortBySimple(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
displayInterest(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
}
/** Round **/
public static double round(double numb1, double numb2) {
double round = ((double) Math.round(numb1*(Math.pow(10, numb2)))/(Math.pow(10, numb2)));;
return round;
}
/** Calculate Simple **/
public static double calculateSimpleInterest(double numb1, double numb2, double numb3) {
double calculateSimpleInterest = ((numb1)*(numb2/100.0)*(numb3/12.0));
return calculateSimpleInterest;
}
/** Calculate Compounded Daily **/
public static double calculateCompoundInterest(double numb1, double numb2, double numb3, double numb4 ) {
double calculateCompoundInterest = (numb1*Math.pow((1.0+((numb2/100.0)/numb4)),(numb4*(numb3/12.0))))-numb1;
return calculateCompoundInterest;
}
/** Get principal amount **/
public static double getPrincipalAmount(double numb1) {
Scanner input = new Scanner(System.in);
double numb2 = 1;
do{System.out.print("Enter Loan Amount: ");
numb2 = input.nextDouble();
if(numb2 > 0);
else{
System.out.println("Data Error: Loan amount must be greater than zero. You entered " +numb2);
}
}while (numb2 < 0);
return numb2;
}
/** Get interest rate **/
public static double getInterestRate(double numb1) {
Scanner input = new Scanner(System.in);
double numb2=1;
do{System.out.print("Enter Yearly Interest Rate (1 to 100 percent): ");
numb2 = input.nextDouble();
double getInterestRate = 0;
if (numb2 >= 0 && numb2 <= 100)
getInterestRate = numb2;
else{
System.out.println("Data Error: Interest rate must be greater than or equal to zero and less than or equal to 100. You entered " +numb2);
}
}while (numb2 <= 0 || numb2 >= 100);
return numb2;
}
/** Get term **/
public static double getTerm(double numb1) {
Scanner input = new Scanner(System.in);
double numb2=1;
do{System.out.print("Enter the Term (in months): ");
numb2 = input.nextInt();
double getTerm = 0;
if (numb2 > 0)
getTerm = numb2;
else{
System.out.println("Data Error: Loan amount must be greater than zero. You entered " +numb2);
}
}while (numb2 <= 0);
return numb2;
}
/** Sort by simple interest **/
public static void sortBySimple(double[][] arrPrincipalAmt ,double[][] arrInterestRate, double[][] arrTerm, double[][] arrSimple, double[][] arrCompoundMonthly, double[][] arrCompoundWeekly, double[][] arrCompoundDaily, double count){
for(int i = 0;i<count;i++)
{
for(int j=i+1; j<count;j++)
{
if(arrSimple[i][j] < arrSimple[i][j])
{
double temp = arrSimple[i][j];
arrSimple[i][j] = arrSimple[i][j];
arrSimple[i][j] = temp;
double temp1 = arrPrincipalAmt[i][j];
arrPrincipalAmt[i][j] = arrPrincipalAmt[i][j];
arrPrincipalAmt[i][j] = temp1;
double temp2 = arrInterestRate[i][j];
arrInterestRate[i][j] = arrInterestRate[i][j];
arrInterestRate[i][j] = temp2;
double temp3 = arrTerm[i][j];
arrTerm[i][j] = arrTerm[i][j];
arrTerm[i][j] = temp3;
double temp4 = arrSimple[i][j];
arrSimple[i][j] = arrSimple[i][j];
arrSimple[i][j] = temp4;
double temp5 = arrCompoundMonthly[i][j];
arrCompoundMonthly[i][j] = arrCompoundMonthly[i][j];
arrCompoundMonthly[i][j] = temp5;
double temp6 = arrCompoundDaily[i][j];
arrCompoundDaily[i][j] = arrCompoundDaily[i][j];
arrCompoundDaily[i][j] = temp6;
double temp7 = arrCompoundWeekly[i][j];
arrCompoundWeekly[i][j] = arrCompoundWeekly[i][j];
arrCompoundWeekly[i][j] = temp7;
}
}
}
}
/** Display Interest **/
public static void displayInterest(double[][] amt ,double[][] interest, double[][] term, double[][] simple, double[][] monthly, double[][] weekly, double[][] arrCompoundDaily, int count){
int i=0;
System.out.println("[Line #] [Principal Amount] [Interest Rate] [Term] [Simple Interest] [Compound Monthly] [Compound Weekly] [Compound Daily]");
do{
System.out.print((i+1)+" ");
System.out.print(amt[i][i]+" ");
System.out.print(+interest[i][i]+" ");
System.out.print(+ term[i][i]+" ");
System.out.print(+simple[i][i]+" ");
System.out.print(+monthly[i][i]+" ");
System.out.print(+weekly[i][i]+" ");
System.out.println(+arrCompoundDaily[i][i]);
i++;
}while(i < count);
}
/**ask yes or no **/
public static boolean askYesNo(String question) {
Scanner input = new Scanner(System.in);
String enteredText;
boolean isAnswerValid;
do{
isAnswerValid = false;
System.out.println(question);
enteredText = input.nextLine();
if (enteredText.length() > 0)
{
enteredText = enteredText.toUpperCase();
if(enteredText.equals("YES") || enteredText.equals("Y") || enteredText.equals("NO") || enteredText.equals("N"))
{
isAnswerValid = true;
}
}
if(isAnswerValid == false)
{
System.out.println("Please enter 'Yes' or 'No'?");
}
} while(isAnswerValid == false);
if(enteredText.equals("YES") || enteredText.equals("Y"))
{
return true;
}
return false;
}
}
Your code looks like an attempt to write C in Java. Java is an OO language, and you will have much more success if you design and write your programs in to make use of that. Data structures that are "smeared" across multiple arrays like that are fundamentally awkward to deal with.
The first thing you need to do to remedy this is to create a class that represents an entry in the arrays.
Trying to fix the program while retaining the current "smeared" data structure design is ... to be blunt ... a waste of time.

Categories

Resources