I am currently working on an assignment for my Java programming class. I seem to have got myself in a bit of a bind. Any assistance in helping me realize what I am doing wrong would be greatly appreciated.
Assignment
Write a program that does the following:
Put the data below into a multi-dimensional array
Prompts the user for the company they would like employee salary statistics.
Write a method that returns the average employee salary as a double. Pass the company number and employee Wages to this method.
Write a method that returns the total employee salary as an int. Pass the company number and employee Wages to this method.
Write a method that returns the number of employees as an int. Pass the company number and employee Wages to this method.
In the main method call the other methods and out put the results.
Keep in mind that I am still new and struggling to understand some of the principles of programming.
When I run the program I am getting locations instead of method calculations (bad output):
Here is what I have so far:
package salaries;
import java.util.Scanner;
public class Salaries {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//declare, instantiate, and define value of multi array [3] [12]
double [][] mSalary = { { 49920, 50831, 39430, 54697, 41751, 36110,
41928, 48460, 39714, 49271, 51713, 38903},
{ 45519, 47373, 36824, 51229, 36966, 40332,
53294, 44907, 36050, 51574, 39758, 53847},
{ 54619, 48339, 44260, 44390, 39732, 44073,
53308, 35459, 52448, 38364, 39990, 47373}};
//declare, instantiate, and define value
//of single array for company names
//and output values to user for selection
String [] company = { "Alhermit", "Logway", "Felter" };
for( int i = 0; i < company.length; i++ )
System.out.println( "Company " + i + " : " +company[i] );
Scanner scan = new Scanner( System.in );
int cCompany;
do{
//ouput for user to select a company
System.out.print("Select company: (0)" +company[0]+ ", (1)"
+company[1]+ "; (2)" +company[2]+ " > ");
//scan user input into cCompany
cCompany = scan.nextInt();
//call number method
num nums = new num();
nums.number(mSalary, cCompany);
//call total method
total sum = new total();
sum.total(mSalary, cCompany);
//call average method
avg cAvg = new avg();
cAvg.average(mSalary, cCompany);
//output statistics to user on selected company
System.out.println( "You have selected the company " + company[cCompany] + ". " );
System.out.println( company[cCompany] + " has " + nums + " of employees." );
System.out.println( "A total employee salary of " + sum + "." );
System.out.println( "The average employee salary is " + cAvg );
}
while( cCompany < 0 || cCompany > 2);
}
}
//total class to calculate
//salary of user selected company
class total {
public static int total( double [][] mSalary, int cCompany ){
//assign variables
int sum = 0;
//for loop to calculate salary total of user input company
for( int j = 0; j < mSalary[cCompany].length; j++ ){
sum += mSalary[cCompany][j];
}
//return statement
return sum;
}
}
//average class to calculate
//average of user selected company
class avg {
public static double average( double [][] mSalary, int cCompany){
//assign variables
int cAvg = 0;
int sum = 0;
int count = 0;
//totals the values for the selected company by
//iterating through the array with count.
while( count < mSalary[cCompany].length){
sum += mSalary[cCompany][count];
count +=1;
}
cAvg = sum / mSalary[cCompany].length;
return cAvg;
}
}
//number class to calculate amount of
//employees in user selected company
class num {
public static int number( double [][] mSalary, int cCompany){
//assign variables
int nums = 0;
//number of employees based on length of colomn
nums = mSalary[cCompany].length;
return nums;
}
}
nums, sum, and cAvg are all instances of classes that you have, you're printing out the instances of those classes.
(By the way - you should change the name of these classes. Classes start with a capital letter. It differentiates them from variables.)
There are two things wrong with this.
You are instantiating a class which contains no data and has no toString method.
You're instantiating a class which only has static methods to return the data from. You don't need to instantiate the class at all; instead, just print the result of the method call.
That would change at least one of these calls to something like:
System.out.println( company[cCompany] + " has " + num.number(mSalary, cCompany); + " of employees." );
I leave the rest as an exercise for the reader.
Related
I am currently taking an intro to java class at my school due to my growing interest in programming.
I am to create a program that takes user input for a min and max integer. I am also to take user input for the size of the array as well as whether or not the user would like both the sorted and unsorted lists printed out.
After I collect this information, I need to generate random values within the given min/max range and sort those values(I had no problem completing these steps).
My code:
//Third Project by John Mitchell
package thirdProject;
//Imported library
import java.util.*;
//First class
public class thirdProject {
//Created scanner and random class as well as variables
public static Scanner scan = new Scanner(System.in);
public static Random rand = new Random();
public static int min, max, rand_num, sum, total, temp, i, j;
public static boolean sorted;
public static int[] values = new int[];
//Allowing for the average output to be of type double
public static double average;
//Main method
public static void main(String[] args) {
//Prompt user to enter minimum value to be sorted
System.out.println("Please enter a minimum value: ");
min = scan.nextInt();
//Prompt user to enter maximum value to be sorted
System.out.println("\nPlease enter a maximum value: ");
max = scan.nextInt();
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
//Prompt the user whether or not they would like both lists
System.out.println("\nWould you like to see both the sorted and unsorted lists? Please enter 'True' for yes or 'False' for no.");
sorted = scan.nextBoolean();
//Prints lists that were generated
if (sorted == true) {
gen_random_val();
System.out.println("\nThe unsorted list is: " + Arrays.toString(values) + ".");
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
} else {
gen_random_val();
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
}
}
//Second method
public static void gen_random_val() {
//For loop that generates values within the range of values given
for(int i = 0; i < values.length; i++) {
values[i] = rand_num = Math.abs(rand.nextInt(max) % (max - min + 1) + min);
sum = sum + values[i];
average = (sum*1.0) / values.length;
}
}
//Third method
public static void sort_values() {
//For loop that sorts values
for(i=0; i<(total-1); i++) {
for(j=0; j<(total-i-1); j++) {
if(values[j] > values[j+1]) {
temp = values[j];
values[j] = values[j+1];
values[j+1] = temp;
}
}
}
}
}
Currently, the hard codes length of 10 values in the array works fine as I have recycled part of my code from a previous project. I am looking for guidance on how to simply make the size determined by user input.
Thank you.
For example you can do this:
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
values = new int[total];
You don't have to give values to variables when you declare them.
I have made it a little further. It turns out I can use loops but not arrays in my assignment. So here's the current version (keep in mind no final calculations or anything yet.) So if you look at the homework method, you can see I am asking for the "number of assignments." Now, for each assignment, I need to ask for and sum both the Earned Score and the Maximum Possible Score. So for instance, if there were 3 assignments, they might have earned scores of 18, 22, and 29, and maximum possible scores of 20, 25, and 30 respectively. I need to grab both using the console, but I don't know how to get two variables using the same loop (or in the same method).
Thanks in advance for your help!
import java.util.*;
public class Grades {
public static void main(String[] args) {
welcomeScreen();
weightCalculator();
homework();
}
public static void welcomeScreen() {
System.out.println("This program accepts your homework scores and");
System.out.println("scores from two exams as input and computes");
System.out.println("your grade in the course.");
System.out.println();
}
public static void weightCalculator() {
System.out.println("Homework and Exam 1 weights? ");
Scanner console = new Scanner(System.in);
int a = console.nextInt();
int b = console.nextInt();
int c = 100 - a - b;
System.out.println();
System.out.println("Using weights of " + a + " " + b + " " + c);
}
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.print("Number of assignments? ");
int totalAssignments = console.nextInt();
int sum = 0;
for (int i = 1; i <= totalAssignments; i++) {
System.out.print(" #" + i + "? ");
int next = console.nextInt();
sum += next;
}
System.out.println();
System.out.println("sum = " + sum);
}
}
I don't know where exactly your problem is, so I will try to give you some remarks. This is how I would start (of course there are other ways to implement this):
First of all - create Assignment class to hold all informations in nice, wrapped form:
public class Assignment {
private int pointsEarned;
private int pointsTotal;
public Assignment(int pointsEarned, int pointsTotal) {
this.pointsEarned = pointsEarned;
this.pointsTotal = pointsTotal;
}
...getters, setters...
}
To request number of assignments you can use simply nextInt() method and assign it to some variable:
Scanner sc = new Scanner(System.in);
int numberOfAssignments = sc.nextInt();
Then, use this variable to create some collection of assignments (for example using simple array):
Assignment[] assignments = new Assignment[numberOfAssignments];
Next, you can fill this collection using scanner again:
for(int i = 0; i < numberOfAssignments; i++) {
int pointsEarned = sc.nextInt();
int pointsTotal = sc.nextInt();
assignments[i] = new Assignment(pointsEarned, pointsTotal)
}
So here, you have filled collection of assignments. You can now print it, calculate average etc.
I hope above code gives you some remarks how to implement this.
Does anyone know how to display the average race time for participants in this simple program?
It would also be great to display the associated runners name with the time.
I think that I have the arrays structure properly and have taken in the user input.
Thanks for any assistance you can provide. Here's my code...
import java.util.Scanner;
public class RunningProg
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Running Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants (2 to 10)");
num=input.nextInt();
// If the user enters an invalid number... display error message...
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)...");
num=input.nextInt();
}
// declare arrays
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
// loop to take in user input for both arrays (name and result)
for (int i = 0 ; i < nameArray.length ; i++)
{
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
This seems like a homework problem so here is how you can solve your problems, in pseudo-code:
Total average race time for participants is calculated by summing up all the results and dividing by the amount of results:
sum = 0
for i = 0 to results.length // sum up all the results in a loop
sum = sum + results[i]
average = sum / results.length // divide the sum by the amount of results to get the average
It would be even better to perform the summation while you read user input and store the runner's names and results. The reason is that it would be more efficient (there would be no need for a second loop to perform the sum) and the code would be cleaner (there would be less of it).
Displaying runners with theirs times can be done by iterating over the two arrays that hold names and results and print values at corresponding index:
for i = 0 to results.length
print "Runner: " + names[i] + " Time: " + results[i]
This works because you have the same amount of results and names (results.length == names.length), otherwise you would end up with an ArrayIndexOutOfBounds exception.
Another way to do this is to use the object-oriented nature of Java and create an object called Runner:
class Runner {
String name;
double result;
Runner(String n, double r) {
result = r;
name = n;
}
}
Then use an array to store these runners:
Runner[] runners = new Runner[num];
for (int i = 0 ; i < num ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
String name = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
double result = input.nextDouble();
runners[i] = new Runner(name, result);
}
Then you can just iterate over the array of runners and print the names and the results... Here is pseudo-code for this:
for i = 0 to runners.length
print runners[i].name + " " + runners[i].result
I have an assignment for my class that goes like this:
"Write a Payroll class that uses the following arrays as fields:
employeeID - An array of seven integers to hold employee identification numbers.
The array should be initialized with the following numbers:
5658845 4520125 7895122 8777541 8451277 1302850 7580489
hours - An array of seven integers to hold the number of hours worked by each employee.
payRate - An array of seven doubles to hold each employee's hourly pay rate.
wages - An array of seven doubles to hold each employee's gross wages.
The class should relate the data in each array through the subscripts.
For example, the number in element 0 of the hours array should be the number of hours worked by the employee
whose identification number is stored in element 0 of the employeeID array.
That same employee's pay rate should be stored in element 0 of the payRate array.
In addition to the appropriate accessor and mutator methods,
the class should have a method that accepts an employee's identification number
as an argument and returns the gross pay for that employee.
I'm having trouble passing values from the program I created. Here is the class:
public class moduleArray2
{
final int NUM_EMPLOYEES = 7;
int[] employeeID = {5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
int[] hours = new int[NUM_EMPLOYEES];
double[] payRate = new double[NUM_EMPLOYEES];
double[] wages = new double[NUM_EMPLOYEES];
int employee = 0;
double wage = 0;
// setHours method
public void setHours(int[] time)
{
time = hours;
}
// setPayRate method
public void setPayRate(double[] pay)
{
pay = payRate;
}
// setWages method
public void setWage(int[] time, int[] pay)
{
for (int index = 0; index < NUM_EMPLOYEES; index++)
wages[index] = time[index] * pay[index];
}
//getEmployeeID method
public int getEmployeeID(int index)
{
return employee;
}
// getWage method
public double getWage(int index)
{
return wage;
}
}
The program is supposed to display each employee number and ask the user to enter that employee's hours and pay rate. It should then display each employee's identification number and gross wages. When I run the program, it simply lists everything as a zero value, including the employee ID numbers.
import java.util.Scanner;
public class moduleArrayDemo2
{
public static void main(String[] args)
{
final int NUM_EMPLOYEES = 7;
int[] time = new int[NUM_EMPLOYEES];
double[] pay = new double[NUM_EMPLOYEES];
// Create new Scanner object
Scanner keyboard = new Scanner(System.in);
// Create employee object
moduleArray2[] employee = new moduleArray2[NUM_EMPLOYEES];
// A loop that creates objects for each element
for (int i = 0; i < employee.length; i++)
employee[i] = new moduleArray2();
for (int i = 0; i < employee.length; i++)
{
System.out.print("Enter hours for Employee #" + employee[i].getEmployeeID(i) +
": ");
time[i] = keyboard.nextInt();
employee[i].setHours(time);
System.out.print("Enter how much Employee #" + employee[i].getEmployeeID(i) +
" makes per hour: ");
pay[i] = keyboard.nextDouble();
employee[i].setPayRate(pay);
}
for (int i = 0; i < employee.length; i++)
{
System.out.println("Employee #" + employee[i].getEmployeeID(i) +
" Wages: " + employee[i].getWage(i));
}
}
}
I can do arrays in a simple program, and I can do classes with programs that create instances of those classes. Arrays in a class...I feel totally lost. How do I reference the arrays in the class to get values in the program itself? Any feedback or suggestions would be greatly appreciated!
First of all you're messing up accessor methods arguments, their actual values and accessed objects.
class ModuleArray2
int[] employeeID = {5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
int NUM_EMPLOYEES = employeeID.length; // I assume you've got it defined somewhere
int[] hours = new int[NUM_EMPLOYEES];
double[] payRate = new double[NUM_EMPLOYEES];
double[] wages = new double[NUM_EMPLOYEES];
// setHours method - will reassign the whole array of `hours` with the provided argument `time` ; I'm leaving this method with a signature that you have provided just to have a place to put my comment on it
public void setHours(int[] time) {
hours = time;
// time = hours; // this is wrong - it would assign class field value to the temporary argument variable `time`, and then just throw it away (since `time` in this scope is temporary)
}
// setHours method - will set working hours in one of an array `hours` elements specified by the provided index - number of an employee it refers to
public void setHours(int employeeNumber, int workedHours) {
hours[employeeNumber] = workedHours;
}
// setPayRate method - same as above
public void setPayRate(int employeeNumber, double payRate) {
payRates[employeeNumber] = payRate;
}
// setWage method - same as above
public void setWage(int employeeNumber, double wage) {
wages[employeeNumber] = wage;
}
// getWage method - will return the wage for employee given by an index in array number
public double getWage(int employeeNumber) {
return wages[employeeNumber];
}
//getEmployeeID method - will return an ID of employee given by an index in array number
public int getEmployeeID(int employeeNumber) {
return employeeID[employeeNumber];
}
//getEmployeeIndexFromID method - will return the index of employee given by his ID number - this is inverse function of the function 'getEmployeeID'
public int getEmployeeIndexFromID(int employeeID) {
int index;
// search implementation goes here
// you should try to write it on your own
return index;
}
}
based on the Tax program change the total variable to an array that accepts 5 double values from the user then pass it to the tax method to get the tax on the total.
I am studying loops and am attempting a sample question here to use only a loop to ask the user to enter in the name of the person, height in feet first, then inches and then to find the tallest. I understand how to do the majority of it.
Could anyone point out where I am going wrong? I began writing the code and realised that I can't declare the persons names without knowing how many people the user will enter. I can't get my head around it.
I want to prompt the user with the questions but also update it to person [2], person [3], person [4] etc. depending on how many people they entered in initially.
Apologies for not wording this correctly. Any help is appreciated. I understand lines 10, 11 and 12 are probably wrong.
class HeightTest
{
public static void main(String[] args)
{
int noOfPeople;
int index;
int feet;
int inches;
String personOne;
String personTwo;
String personThree;
System.out.print("Enter a number of people ");
noOfPeople = EasyIn.getInt();
for (index = 1; index <=noOfPeople; index++)
{
System.out.println("Enter the name of person " + index);
personOne = EasyIn.getString();
System.out.println("Enter feet portion for " + personOne);
feet = EasyIn.getInt();
System.out.println("Enter inches portion for " + personOne);
inches = EasyIn.getInt();
}
}
}
You have a very good start. All you need to do now is keep track of the heights that are entered, and compare them to the largest one input so far. If the height for the current loop iteration is larger than the current largest, store it as the largest.
In pseudocode:
int largestHeightInches = 0;
for( i = 1; i <= noOfPeople; index++ ) {
currentHeightFeet = GetInt();
currentHeightInches = GetInt();
currentHeight = currentHeightInches + currrentHeightFeet * 12;
if( largestHeightInches < currentHeight ) {
largestHeightInches = currentHeight;
}
}
You would have to create an array of Persons to acheive what you want.
Here's a snippet.
Create a class called Person
public class Person
{
int index;
int feet;
int inches;
String name;
}
create a main Test class to contain your main method, and do something like this
public class Main{
public static void main (String[] args)
{
// get the number of people in noOfPeople as you do now.
Person[] pArray= new Person[nOfPeople]
for(Person p: pArray)
{
System.out.println("Enter the name of person " + index);
p.name = EasyIn.getString();
// ...etc
}
}
}