Method Call on an Array to get an Average - java

Problem:
Write a program to calculate the wages of 5 hourly-paid employees in the company. Your program will input for each of the 5 employees the employee ID, the number of hours they worked and his/her pay rate. These data are to be stored into 3 parallel arrays: employee_ID, hours, and payrate. Your program will then call a method to calculate the wage of each employee, the results will be stored in another parallel array. Output the 4 parallel arrays side-by-side. Your program will then call 3 methods: findAve to determine the average pay of the 5 employees, findMax and findMin to determine and return the ID of the employee who receives the highest and lowest pay respectively. The results will be outputted in the main method.
Trouble with: How do I implement a method call to get an array average?
Code:
public class Employees {
public static void main(String[] args) {
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
int[] id;
id = new int[5];
int[] payrate;
payrate = new int[5];
int[] wage;
wage = new int[5];
final int EMPLOYEES = 5; // Number of employees
int[] hours = new int[EMPLOYEES]; // Array of hours
System.out.println("Enter the hours worked by " +
EMPLOYEES + " employees.");
// Get the hours for each employee.
for (int index = 0; index < EMPLOYEES; index++)
{
System.out.print("Employee " + (index + 1) + ": ");
hours[index] = keyboard.nextInt();
}
System.out.println("The hours you entered are:");
// Display the values entered.
for (int index = 0; index < EMPLOYEES; index++)
System.out.println(hours[index]);
System.out.println("Enter the payrate worked by " +
EMPLOYEES + " employees.");
// Get the payrate for each employee.
for (int index1 = 0; index1 < EMPLOYEES; index1++)
{
System.out.print("Employee " + (index1 + 1) + ": ");
payrate[index1] = keyboard.nextInt();
}
System.out.println("The payrate you entered are:");
// Display the values entered.
for (int index1 = 0; index1 < EMPLOYEES; index1++)
System.out.println(hours[index1]);
System.out.println("Enter the wage worked by " +
EMPLOYEES + " employees.");
// Get the wage for each employee.
for (int index2 = 0; index2 < EMPLOYEES; index2++)
{
System.out.print("Employee " + (index2 + 1) + ": ");
wage[index2] = keyboard.nextInt();
}
System.out.println("The wage you entered are:");
// Display the values entered.
for (int index2 = 0; index2 < EMPLOYEES; index2++)
System.out.println(wage[index2]);
}
//A method that calculates and returns the average of a passed array.
public static void calculateAverage (int[] wage)
{
int average = 0;
int total = 0;
for (int i=0; i<=wage.length; i++)
{
total += wage[i];
}
average = (total / wage.length);
return;
}
System.out.println(average);
}

You've done most of it in calculateAverage() already. But there's a couple issues.
You want to set your for loop to be i<wage.length rather than <= because arrays start at 0, so when i = length of the actual array, you'll get an out of bounds exception. ie, if there's 5 employees, wage.length == 5 where as the indexes are 0, 1, 2, 3, 4.
you're not returning anything. You've calculated the average so return it.
You'll need to set the return type other than void. I would also recommend NOT using an integer just in case your average turns out to be a decimal. You'd have to cast your int values first before calculation.
Rough fixes:
public static double calculateAverage (int[] wage) {
double average = 0;
int total = 0;
for (int i=0; i<wage.length; i++) {
total += wage[i];
}
average = (double) total / (double) wage.length;
return average;
}
Your system.out.println afterwards also can't access average since it's out of scope of the method. You can call it like this:
System.out.println(calculateAverage(wage));

Your calculateAverage method is returning void, which means it doesn't return a value. You should make it return the average.
PS: for monetary values, I suggest you to use the double instead of int. Double accept decimal values when int does not.
public static int calculateAverage (int[] wage)
{
int average = 0;
int total = 0;
for (int i=0; i<wage.length; i++)
{
total += wage[i];
}
average = (total / wage.length);
return average;
}

Related

Display Min/Max array

The final output will show who has the highest grade and who has the lowest grade.
I'm lost on how to call the lowest name/grade to the final output.
In the code I have some comments on where I'm stuck with the "currentMinIndex", the "currentMaxIndex" works just fine and will show it to the final output. I tried to mirror it but it isn't going how I expected. Not sure if something with "(int k = 1; k>= m; k++)" is incorrect.
import java.util.*;
public class MyArrayEX {
// Sort grades lowest on top
public static int[] reverseInt(int[] array) {
int[] input = new int[array.length];
for (int i = 0, j = input.length - 1; i < array.length; i++, j--) {
input[j] = array[i];
}
return input;
}
public static void main(String[] args) {
// Scanners
Scanner input = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
// Input amount
System.out.print("\nEnter number of students: ");
int numOfStu = input.nextInt(); // Number of Students
int[] grades = new int[numOfStu];
String[] names = new String[numOfStu];
// Start loop, amount is based off of "numOfStu"
for (int i = 0; i < numOfStu; i++) {
System.out.print("\rEnter student first name: ");
String name = keyboard.next();
System.out.print("Enter the students grade: ");
int grade = input.nextInt();
// Assigning i
names[i] = name;
grades[i] = grade;
//System.out.println("");
}
// This is the area that sorts it from least to greatest
// i is the indexed value of the last number in array
for (int i = grades.length - 1; i > 0; i--) {
// Resets both to 0 to start at the beginning of the array
int currentMax = grades[0];
int currentMaxIndex = 0;
// i is back-limit that gets chopped off by one each time
for (int k = 1; k <= i; k++) {
if (currentMax < grades[k]) {
currentMax = grades[k];
currentMaxIndex = k;
}
}
// This is where im lost on how to call the min value
// Trying to mirror the one above but using it
// to show the minimum grade along with the name
for (int m = grades.length - 1; i > 0; i--) {
int currentMin = grades[0];
int currentMinIndex = 0;
// Min grades
for (int k = 1; k >= m; k++) {
if (currentMin < grades[m]) {
currentMin = grades[m];
currentMinIndex = m;
}
}
// After largest number is found, assign that number to i
// Im trying to have the final output show the min/max grade with who has it
// Would the MinIndex be assigned to a different variable?
grades[currentMaxIndex] = grades[i];
grades[currentMinIndex] = grades[m];
grades[i] = currentMax;
grades[m] = currentMin;
String highName = names[currentMaxIndex];
String lowName = names[currentMinIndex];
names[currentMaxIndex] = names[i];
names[currentMinIndex] = names[m];
names[i] = highName;
names[m] = lowName;
// This shows the name and grade for the highest number
System.out.print("\rThe highest grade is " + highName + " with a " + currentMax);
// Unsure how to call this.
System.out.println("\r and the Lowest grade is " + lowName + " with a " + currentMin);
}
}
input.close();
keyboard.close();
}
}
Your code has multiple problems. First is with the 2 scanners that you are using for same System.in input stream and second you are using nested loops to find the min/max values which is totally unnecessary. Since the question is about finding the min/max so I will focus on that part only and for the scanner I would say remove the keyboard scanner and use only input scanner. Anyways, use the following code block to find the maximum and minimum grades with names:
int currentMaxIndex = 0;
int currentMinIndex = 0;
// Get min max
for (int i = 1; i<grades.length; i++) {
if (grades[currentMaxIndex]<grades[i]) {
currentMaxIndex=i;
}
if (grades[currentMinIndex]>grades[i]) {
currentMinIndex=i;
}
}
String highName = names[currentMaxIndex];
String lowName = names[currentMinIndex];
int currentMax = grades[currentMaxIndex];
int currentMin = grades[currentMinIndex];
System.out.print("\rThe highest grade is " + highName + " with a " + currentMax);
System.out.println("\r and the Lowest grade is " + lowName + " with a " + currentMin);
The approach is quite simple. We first aasume that the first element in the grades array is min and max then we loop to the remaining elements from 1 to grades.length and compare the index min/max to the current index element values and accordingly change our min/max indices. If the current index value is greater than currentMaxIndex then we copy it to currentMaxIndex and same but opposite for currentMinIndex. So in the end we will have the highest and lowest value indices of grades array. The complete code is here https://ideone.com/Qjf48p

2D array column average java

I have 2 arrays, String[][] names and int[][] grades, to store the names and grades of a class I am trying to print as a table in a much longer code. I was able to calculate the average of each row with a method I called in the main. I'm having a hard time figuring out how to do the average of each column though. Any suggestions would be appreciated. For the row averages I wrote a method:
//determine average for each student
public double rowAverage(int[] rowOfGrades) {
int total = 0;
//sum grades for each student
for(int grade : rowOfGrades){
total += grade;
}
//return average of student grades
return (double) total/rowOfGrades.length;
}//end getAverage
and then printed it in my main with
//creates rows and columns of text for array names and grades
for(int student=0; student<names.length; student++) {
System.out.printf("%s",names[student]); //student name
for(int test : grades[student]) {
System.out.printf("\t%7d",test); //test grades
}
//call method getAverage to calculate students grade average
//pass row of grades as the argument to getAverage
double average = rowAverage(grades[student]);
System.out.printf("%12.2f", average);
}
For each test you have to iterate over the students:
for (int test = 0; test < grades.length; test++) {
int total = 0;
for(int student=0; student<names.length; student++) {
total += grades[student][test]
}
double avgForTest = (double) total/names.length;
}
Make a new array w/ the values for the column you are interested in; rowAverage will compute the average for that array (thus that column). Repeat for each column.
to access each column of a row you will have to access its length field e.g. names[student].length
example
int[][] towers = new int[8][8];
int myNumber=25;
for(int row=0;row<towers.length;++row)
{
for(int column=0;column<towers[row].length;++column)
{
if(myNumber==towers[row][column])
{
System.out.println("I found you");
column=towers[row].length;
row=towers.length;
}
}
}
You can try like
for (int i = 0; i < 2; i++) {
int rowSum = 0;
int colSum = 0;
double rowAvg = 0.0;
double colAvg = 0.0;
for (int j = 0; j < 2; j++) {
rowSum += arr[i][j];
colSum += arr[j][i];
}
rowAvg = rowSum / 2.0;
colAvg = colSum / 2.0;
System.out.println(i + " row average: " + rowAvg);
System.out.println(i + " column average: " + colAvg);
}

Need to print out max value of an array and the name of which index holds the highest value

So the purpose of my program is to create an array for 5 Salespeople. The user is prompted to enter in the total sales for each Person. Then, I need to print out the sum, average, lowest sale and highest sale. I can get the average, the sum of all the sales, and have managed to print the largest value of the array, but I need it to say, for example, Salesperson 2 had $50,000 in sales. What I have now is "50,000 had $50,000" if that makes since. So value 3 of the array (salesperson 2, as I have not included a Salesperson 0) is 50,000. My array:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int SALESPEOPLE = 6;
int[] sales = new int[SALESPEOPLE];
int sum;
for (int i = 1; i < sales.length; i++) {
System.out.print("Enter sales for salesperson " + i + ": ");
sales[i] = scan.nextInt();
}
}
And the get max value
for (int i = 1; i < sales.length; i++) {
System.out.println(i + " \t" + sales[i]);
sum += sales[i];
}
System.out.println("The highest sale was");
int maxValue = getMaxValue(sales);
int maxValueName = getMaxValueName(sales);
System.out.println("Name: " + maxValueName + "Sale: " + maxValue);
System.out.println("The lowest sale was");
int minValue = getMinValue(sales);
System.out.println(minValue);
Max Value
public static int getMaxValue(int[] array) {
int maxValue = array[1];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
public static int getMaxValueName(int[] array) {
int maxValueName = array[1];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValueName) {
maxValueName = array[i];
}
}
return maxValueName;
}
You have some number of personnel in your sales force. Each of these persons has a name and also has made some amount of sales (some sort of a number). So it makes no sense to store just a number in your array.
Define a type of object that contains a String (for a person's name) and a number (for how much they sold). That is the kind of object you should put in your array. It makes no sense to write in Java and then not use anything that has even a hint of object-oriented design about it.
Notice that once you have an array of these objects, if you can find the object that has the highest sales number then you also have found the one that has the name of the person you want to print. Now ask yourself why you would want to write two separate functions, each of which has to search the array to find that object.

Average Class not working

What is wrong here? It's not printing test scores in descending order, nor am I getting a value for mean. Shows up 0.0
Her are the instructions that I was given:
This class will allow a user to enter 5 scores into an array. It will then rearrange the data in descending order and calculate the mean for the data set.
Attributes:
• data[]—the array which will contain the scores
• mean—the arithmetic average of the scores
Methods:
• Average—the constructor. It will allocate memory for the array. Use a for loop to repeatedly display a prompt for the user which should indicate that user should enter score number 1, score number 2, etc. Note: The computer starts counting with 0, but people start counting with 1, and your prompt should account for this. For example, when the user enters score number 1, it will be stored in indexed variable 0. The constructor will then call the selectionSort and the calculateMean methods.
• calculateMean—this is a method that uses a for loop to access each score in the array and add it to a running total. The total divided by the number of scores (use the length of the array), and the result is stored into mean.
• toString—returns a String containing data in descending order and the mean.
• selectionSort—his method uses the selection sort algorithm to rearrange the data set from highest to lowest.
import java.util.Scanner;
public class Average
{
private int[] data;
private double mean;
private int total = 0;
public Average()
{
data = new int[5];
Scanner keyboard = new Scanner(System.in);
for(int i = 0; i < data.length; i++)
{
System.out.print("Enter score number " + (i + 1) + ": ");
data[i] = keyboard.nextInt();
}
}
public void calculateMean()
{
int i, s = 0;
for(i = 0; i < data.length; i++)
{
s = s + data[i];
}
mean = (double)s / (data.length);
}
public void selectionSort()
{
int maxIndex;
int maxValue;
for(int startScan = 0; startScan < data.length - 1; startScan++)
{
maxIndex = startScan;
maxValue = data[startScan];
for(int index = startScan + 1; index < data.length; index++)
{
if(data[index] > maxValue)
{
maxValue = data[index];
maxIndex = index;
}
}
data[maxIndex] = data[startScan];
data[startScan] = maxValue;
}
}
public String toString()
{
String output;
output = "The test scores in descending order are \n";
for(int i = 0; i < data.length; i++)
{
output = output + data[i] + " ";
}
output = output + "\nThe average is " + mean;
return output;
}
}
You need methods that return and take in values with your methods. Here is a little mock-up of your program to show what I mean:
public static void main(String... args)
{
System.out.println(calculateMean(getData()));
}
public static int[] getData()
{
data = new int[5];
Scanner s = new Scanner(System.in);
for (int i = 0; i < data.length; i++)
{
System.out.print("Enter score number " + (i++) + ": ");
data[i] = Integer.parseInt(s.nextLine());
}
s.close();
return data;
}
public static double calculateMean(int[] data)
{
int s = 0;
for (int i = 0; i < data.length; i++)
{
s += data[i];
}
return mean = (double) s / (data.length);
}
The getData() method gets all the information we need from the user, and then we take that data and we pass it right along to the calculateMean() method. This, in turn, spits out the average of all the scores for us. Then all we do is print that. I'll leave the rest up to you since this looks like homework.
Trial run:
Input: 4, 67, 3, 7, 3 (comma's indicate new line)
Output: 16.8
All you need is
public static void main(String[] args){
Average avg = new Average();
avg.selectionSort();
avg.calculateMean();
System.out.println(avg);
}
Everything is in place. I second #HeatfanJohn
It looks like you are not executing the calculateMean() method call first like that:
public static void main(String[] args) {
Average average = new Average();
average.calculateMean();
average.selectionSort();
System.out.println(average.toString());
}
You never make a call to calculateMean(), that is why the average is zero. In you main or where ever you create your instance of Average, you need to call calculateMean() before referencing Average.toString().

Displaying two arrays in tester class

I have six tasks that need to be completed but i do not know how to display them. I haave all the code to calculate each task needed but when it comes to applying them to my tester class i am stuck. below is my code for the original class. these are the task that need to be done:
Display the original data set, as shown in the table.
The average profit for the supermarket chain.
The city with the highest profit.
A list of all the cities with profit at, or above the average.
The cities and their profit listed in descending order of the profits.
Make a horizontal graph showing the performance of each supermarket
Please help because ive been doing this for the last couple days and still havent been able to do anything... i must be stupid please help
package supermarkets;
public class Supermarkets
{
private String[] city = {"Miami", "Sunrise", "Hollywood",
"Tallahassee", "Jacksonville", "Orlando", "Gainesville", "Pensacola",
"Ocala", "Sebring"};
private double[] profit = {10200000, 14600000, 17000000, 6000000,
21600000, 9100000, 8000000, 12500000, 2000000, 4500000};
public Supermarkets(String[] c, double[] p)
{
//array for the city
city = new String[c.length];
for (int i = 0; i < c.length; i++)
city[i] = c[i];
//array for the profits
profit = new double[p.length];
for(int i = 0; i < p.length; i++)
profit[i] = p[i];
}
//sums up the profits from the cities
public double sumArray()
{
double sum = 0;
for (int i = 0; i < profit.length; i++)
sum = sum + profit [i];
return sum;
}
//calculates the average of the profits from the cities
public double average()
{
return sumArray() / profit.length;
}
//shows highest profit
double findHighestProfit()
{
double highest = profit[0];
for(int i = 1; i < profit.length; i++)
{
if ( profit [i] > highest )
highest = profit [i];
}
return highest;
}
//gives the above average profit
public String aboveAvarage()
{
String s = "";
double avg = average();
for (int i = 0; i < profit.length; i++)
if (profit [i] > avg)
s = s + city[i] + " " + profit[i] + "\n";
return s;
}
//creates a graph showing city and profits
public String makeGraph()
{
String s = "";
for (int i = 0; i < profit.length; i++)
{
s = s + city[i] + " ";
int x = (int) Math.floor( profit[i] );
for(int j = 1; j <=x; j++)
s = s + "*";
s = s + "\n";
}
return s;
}
//resets profits position from least to greatest
public int findPosition(int startScanFrom)
{
int position = startScanFrom;
for (int i = startScanFrom + 1; i < profit.length; i++)
if (profit[i] < profit[position])
position = i;
return position;
}
//swaps values for city and profits
public void swap(int i, int j)
{
// Swap the profits
double temp = profit[i];
profit[i] = profit[j];
profit[j] = temp;
// Swap the cities
String str = city[i];
city[i] = city[j];
city[j] = str;
}
}
You didn't provide your test/driver program, so I had to make a lot of assumptions.
Just write a method that loops through the two arrays and prints the values.
Your method to find the average profit looks fine.
You have a method to find the highest profit, but you need to display the city. I added a method to find the city with the highest profit.
//shows city with highest profit
String findHighestProfitCity()
{
double highest = profit[0];
String c = city[0];
for(int i = 1; i < profit.length; i++)
{
if ( profit [i] > highest ) {
highest = profit [i];
c = city[i];
}
}
return c;
}
This is a fairly straightforward method. Once you calculate the average, just loop through the city/profit arrays and display any cities that have a profit higher than the average.
The easiest way to do this with the data organized in two arrays would be to write a custom sort routine that sorts the profit array and makes a swap in the city array each time one is necessary in profit.
The test data you put in your city and profit arrays is way too big to display graphically. Your makeGraph() method tries to draws x asterisks for each value in profit. Even after cutting five zeroes off of each value, that still didn't fit on my screen, so I modifed that method to only draw x/10 asterisks for each profit
for(int j = 1; j <= x/10; j++)
s = s + "*";
Here's a test/driver program that you can use as a starting point.
package supermarkets;
public class SupermarketDriver {
/**
* #param args
*/
public static void main(String[] args) {
String[] cities = {"Miami", "Sunrise", "Hollywood",
"Tallahassee", "Jacksonville", "Orlando", "Gainesville", "Pensacola",
"Ocala", "Sebring"};
double[] profits = {102, 146, 170, 60, 216, 91, 80, 125, 20, 45};
Supermarkets sm = new Supermarkets(cities, profits);
System.out.println(sm.makeGraph());
System.out.println("Average profit: " + sm.average());
System.out.println();
System.out.println("Highest profit city: " + sm.findHighestProfitCity() + ", " + sm.findHighestProfit());
}
}

Categories

Resources