Complete newbie here guys. I'm working on a Java program to prompt the user for 3 variables which are used to calculate a future investment's value. Everything works perfectly, except when it comes time to put both my datatypes into ONE array.
Here's what the output SHOULD look like:
Year Future Value
1 $1093.80
2 $1196.41
3 $1308.65
...
This is what mine looks like:
Year 1
Future Value 1093.81
Year 2
Future Value 1196.41
Year 3
Future Value 1308.65
...
My year is an int value and my Future value is a double (rounded). I've been sitting here racking my brain and all the forums I can find and haven't been successful. Every time I put both value into an array I get an error about putting two different datatypes together. Any insight would be greatly appreciated. Below is the code for my full program:
import java.util.Scanner;
class investmentValue {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter investment amount: $");
double i = s.nextDouble();
System.out.print("Enter percentage rate: ");
double r = s.nextDouble()/100;
System.out.print("Enter number of years: ");
int y = s.nextInt();
for (y=1; y<=30; y++) {
double f = futureInvestmentValue(i,r,y);
System.out.println("Year " + y);
System.out.println("Future Value " + f);
}
}
public static double futureInvestmentValue (double investmentAmount, double monthlyInterestRate, int years){
double value=1;
value = investmentAmount*Math.pow((1+(monthlyInterestRate/12)),(years * 12));
double roundValue = Math.round(value*100.0)/100.0;
return roundValue;
}
}
One solution is to start by implementing a pad function. Something like,
public static String pad(String in, int len) {
StringBuilder sb = new StringBuilder(len);
sb.append(in);
for (int i = in.length(); i < len; i++) {
sb.append(' ');
}
return sb.toString();
}
Now we can combine that with String.format() to get the dollars and cents, use a consistent printf() for the header and output lines. To get something like,
// Print the header.
System.out.printf("%s %s%n", pad("Year", 12), "Future Value");
for (int y = 1; y <= 30; y++) {
String year = pad(String.valueOf(y), 13); // <-- One more in your alignment.
String fv = String.format("$%.2f", futureInvestmentValue(i,r,y));
System.out.printf("%s %s%n", year, fv);
}
The System.out.println command isn't the only method available to you!
Try this in your loop:
System.out.print(y); // note that we use print() instead of println()
System.out.print('\t'); // tab character to format things nicely
System.out.println(f); // ok - now ready for println() so we move to the next line
Naturally, you'll want to do something similar to put your headings in.
PS - I'm pretty sure this is just an output formatting question - you don't really want to put all these values into a single array, right?
Given that you really are looking for formatted output, it may be better to use the printf() method.
The following inside the loop (instead of the 3 lines I wrote above) should do the trick (untested - I haven't used printf() format strings in a long, long time).
System.out.printf("%i\t$%0.2f", y, f);
EDIT: edited to answer your question in the comments about constructors... You should also check out this for further understanding
You could create a class that will hold both of the arrays...
This would give you a single object, let's call it StockData, that holds two arrays for the two separate types you need. You need to create the object once and then insert the data separately by type.
class StockData {
double[] data1;
int[] data2;
// default constructor
StockData() {
}
// constructor
StockData(double[] data1, int[] data2) {
this.data1 = data1;
this.data2 = data2;
}
// getters, setters...
}
Then you add data to an array of its type:
// using default constructor to add a single value to both arrays
StockData sd = new StockData();
sd.data1[INDEX_X] = YOUR_DOUBLE;
sd.data2[INDEX_X] = YOUR_INT;
// using default constructor to add all data to both arrays
StockData sd = new StockData();
sd.data1 = YOUR_ARRAY_OF_DOUBLE;
sd.data2 = YOUR_ARRAY_OF_INTS;
// using constructor to add all array data directly
StockData sd = new StockData(YOUR_ARRAY_OF_DOUBLE, YOUR_ARRAY_OF_INTS);
You could also have an object that will hold the double and int value, so the object will represent a single stock information of 2 values and then create an array containing those objects...
class StockData {
double data1;
int data2;
// default constructor same as before
// constructor
StockData(double data1, int data2) {
this.data1 = data1;
this.data2 = data2;
}
// getters, setters...
}
// ...
Adding data:
// create an array of StockData objects
StockData[] sd = new StockData[TOTAL_AMOUNT_OF_DATA];
// ... obtain your data
// using default constructor to add a single value to the array
sd[INDEX_X] = new StockData();
sd[INDEX_X].data1 = YOUR_DOUBLE;
sd[INDEX_X].data2 = YOUR_INT;
// using constructor to add all data directly
sd[INDEX_X] = new StockData(YOUR_DOUBLE, YOUR_INT);
If you want the program to have an specific format you could try to change your code and put this where your for is:
System.out.println("Year Future Value");
for (y=1; y<=30; y++) {
double f = futureInvestmentValue(i,r,y);
System.out.print(y);
System.out.println(" " + f);
}
this way you will have your output in the format you need without using arrays. But if you want to do an array for this you could declare an array of objects and create a new object with two attributes (year and future value)
Also your class name is investmentValue and it is recommended that all classes start with upper case it should be InvestmentValue
I hope that this can help you
A fun data structure you would be able to use here is a Map (more specifically in Java, a HashMap). What you are doing is associating one value with another, an integer to a double, so you could make something that looks like this:
Map<Integer, Double> myMap = new HashMap<>();
This would take the year as the integer, and the double as the price value, and you could iterate over the map to print each value.
Additionally if you really are looking for a "multidata type array," Java automatically casts from integer to double should you need to. For example:
int i = 2;
double[] arr = new double[2];
arr[0] = 3.14
arr[1] = i;
The above code is perfectly valid.
Related
I'm trying to display in the Message dialog on the JOptionPane the highest number of sales from my array of sales.
And I also want to show in which month they happened, but I am failing to find a way to display the month.
public static void main(String[] args) {
int[] CarSales= {1234,2343,1456,4567,8768,2346,9876,4987,7592,9658,7851,2538};
String [] Months = {"January","February","March","April","May","June"
,"July ","August","September","October","November","December" };
int HighNum = CarSales[0];
for(int i = 0; i < CarSales.length; i++)
{
if(CarSales[i] > HighNum)
{
HighNum = CarSales[i];
}
}
JOptionPane.showMessageDialog(null,"The highest car sales value is :"+HighNum +
"-which happened in the month of");
}
Use the Power of Objects
Avoid using parallel arrays in Java. It brings unnecessary complexity, makes the code brittle and less maintainable.
Your code doesn't automatically become object-oriented just because of the fact that you're using an object-oriented language.
Objects provide you an easy way of structuring your data and organizing the code (if you need to implement some functionality related, to a particular data you know where it should go - its plane is in the class representing the data).
So, to begin with, I advise you to implement a class, let's call it CarSale:
public static class CarSale {
private Month month;
private int amount;
// getters, constructor, etc
}
Or, if you don't need it to be mutable, it can be implemented as a Java 16 record. In a nutshell, record is a specialized form of class, instances of which are meant to be transparent carriers of data (you can not change their properties after instantiation).
One of the greatest things about records is their concise syntax. The line below is an equivalent of the fully fledged class with getters, constructor, equals/hashCode and toString (all these would be generated for you by the compiler):
public record CarSale(Month month, int amount) {}
java.time.Month
You've probably noticed that in the code above, property month is not a String. It's a standard enum Month that resides in java.time package.
When you have a property that might have a limited set of values, enum is always preferred choice because contrary to a plain String, enum guards you from making typo and also enums have an extensive language support. So you don't need this array filled with moth-names.
That's how your code might look like:
CarSale[] carSales = {
new CarSale(Month.JANUARY, 1234),
new CarSale(Month.FEBRUARY, 2343),
new CarSale(Month.MARCH, 1456),
// ...
};
// you might want to check if carSales is not is empty before accessing its first element
CarSale best = carSales[0];
for (CarSale sale: carSales) {
if (sale.getAmount() > best.getAmount()) best = sale;
}
JOptionPane.showMessageDialog(null,
"The highest car sales value is :" + best.getAmount() +
" which happened in the month of " + best.getMonth());
Note
Try to keep your code aligned with Java naming conventions. Only names of classes and interface should start with a capital letter.
In case if you've heard from someone that usage of parallel arrays can improve memory consumption, then I would advise to examine this question dipper and take a look at questions like this Why use parallel arrays in Java? In case of such tiny arrays the only thing are disadvantages of a fragile code.
There are multiple solutions but i'll give you the simplest based on your structure.
Just declare one String variable and assign the value whenever you change the highest num.
public static void main(String[] args) {
int[] CarSales= {1234,2343,1456,4567,8768,2346,9876,4987,7592,9658,7851,2538};
String [] Months = {"January","February","March","April","May","June"
,"July ","August","September","October","November","December" };
int HighNum = CarSales[0];
String month = Months[0];
for(int i = 0; i < CarSales.length; i++)
{
if(CarSales[i] > HighNum)
{
HighNum = CarSales[i];
month = Months[i];
}
}
JOptionPane.showMessageDialog(null,"The highest car sales value is :"+HighNum +
"-which happened in the month of " + month);
}
Keep an index. Whenever you change the highest found, update the index.
public static void main(String[] args) {
int[] CarSales= {1234,2343,1456,4567,8768,2346,
9876,4987,7592,9658,7851,2538};
String [] Months = {"January","February","March","April","May","June"
,"July ","August","September","October","November","December" };
int HighNum = CarSales[0];
int highMonth = 0;
for(int i = 0; i < CarSales.length; i++)
{
if(CarSales[i] > HighNum)
{
HighNum = CarSales[i];
highMonth = i;
}
}
JOptionPane.showMessageDialog
(null,"The highest car sales value is :"+HighNum +
"-which happened in the month of " + Months[highMonth]);
}
Table table;
class AirPollution{
String place;
float NO2;
float CO;
int AP;
AirPollution(String p,float x, float y, int c){
place=p;
NO2=x;
CO=y;
AP=c;
}
}
void loadData(){
String[] data=loadStrings("airPollution.txt");
AirPollution[] AP=new AirPollution[5];
for(int i=0;i<data.length;i++){
//Part I don't know
}
}
Exactly, I am studying processing.
Below is the contents of the txt file
place,NO2(ppm),CO(ppm),Air pollution
Nowon-gu,0.024,0.6,26
Dobong-gu,0.02,0.4,12
Seocho-gu,0.018,0.3,18
Gwanak-gu,0.022,0.5,20
Guro-gu,0.017,0.3,21
This data exists, and I try to input values from the second line excluding the first line.
For example
AP[0].place="Nowon-gu"
AP[0].NO2=0.024
AP[0].CO=0.6
AP[0].AP=26
AP[1].place="Dobong-gu"
I hope this way. In this case, should I put in each one without using the split function?
Or should I use another method?
I see no reason to not use split.
In your loop, I would first split the current data item on a ,, then just add each part to an AirPollution object which finally gets added to the AP array.
Note that in my solution, I initialised your for loop at the index 1 opposed to 0. I'm making the assumption here that loadStrings produces the output that you included, which includes the header row, and I'm assuming that you don't actually want this header row in the AP array.
Note that now you might want to put some sort of check to ensure that data.length is greater than 1 before entering the for loop.
Note that I've also changed your hard coded array size from 5 to data.length - 1. The assumption here is that the array size shouldn't always be 5, there will always be a header row, and you don't want to include the header row in the array.
The below code should do exactly as you've asked, but see my comment after the code block for some extra points:
void loadData() {
String[] data = loadStrings("airPollution.txt");
AirPollution[] AP = new AirPollution[data.length - 1];
for (int i = 1; i < data.length; i++) {
String[] dataParts = data[i].split(",");
AirPollution airPollution = new AirPollution(
dataParts[0],
Float.parseFloat(dataParts[1]),
Float.parseFloat(dataParts[2]),
Integer.parseInt(dataParts[3])
);
AP[i - 1] = airPollution;
}
}
BUT, from your code, I see that this loadStrings method isn't actually defined in the AirPollution class, you want loadStrings to return void and the loadStrings method doesn't take in any argument. This means, you can populate the AP array just fine with the above code, but your code can't actually do anything with it.
Looking from the code context, I would assume that you want the loadStrings function to actually return the AirPollution array so that you can use it in whatever class is wrapping the AirPollution class. I would make a slight tweek to the above code to reflect this (add return statement and change return type):
AirPollution[] loadData() {
String[] data = loadStrings("airPollution.txt");
AirPollution[] AP = new AirPollution[data.length - 1];
for (int i = 1; i < data.length; i++) {
String[] dataParts = data[i].split(",");
AirPollution airPollution = new AirPollution(
dataParts[0],
Float.parseFloat(dataParts[1]),
Float.parseFloat(dataParts[2]),
Integer.parseInt(dataParts[3])
);
AP[i - 1] = airPollution;
}
return AP;
}
Let me know if anything is unclear!
In addition to Ibz' detailed answer (+1) explaining manual parsing, here's a version using Processing's Table class which can be loaded using loadTable():
Table table;
void setup() {
// load table and specify the first row is a header
table = loadTable("Airpollution.csv", "header");
int rowCount = table.getRowCount();
// for each row
for (int i = 0; i < rowCount; i++) {
// access the row
TableRow row = table.getRow(i);
// access each piece of data by column name...
String place = row.getString("place");
float no2 = row.getFloat("NO2(ppm)");
float co = row.getFloat("CO(ppm)");
// ...or column index
int airPollution = row.getInt(3);
// print the data
println(i, place, no2, co, airPollution);
}
}
Now that you can access the parsed data, you can plug it to instances AirPollution:
Table table;
void setup() {
// load table and specify the first row is the CSV header
table = loadTable("Airpollution.csv", "header");
int rowCount = table.getRowCount();
// use row count (as .csv data could change)
AirPollution[] AP = new AirPollution[rowCount];
// for each row
for (int i = 0; i < rowCount; i++) {
// access the row
TableRow row = table.getRow(i);
// initialize AirPollution data with row data
AP[i] = new AirPollution(row.getString("place"),
row.getFloat("NO2(ppm)"),
row.getFloat("CO(ppm)"),
row.getInt(3));
// print the data
println("row index",i,"data",AP[i]);
}
}
class AirPollution {
String place;
float NO2;
float CO;
int AP;
AirPollution(String p, float x, float y, int c) {
place=p;
NO2=x;
CO=y;
AP=c;
}
// display nicely when passing this instance to print/println
String toString(){
// %.3f = floating point value with 3 decimal places
return String.format("{ place=%s, NO2=%.3f, CO=%.3f, AP=%d} ", place, NO2, CO, AP);
}
}
Notice I've renamed the file from .txt to .csv: this extension might help preview/test the data using OpenOffice Calc, Excel, Google Sheets, etc.
Have fun visualising the data.
If you want to learn more about the Table class, other the reference, also check out Processing > Examples > Topics > Advanced Data > LoadSaveTable
I want to do the average of 9 textfields and also the sum of them and place them in 2 other textfields by using a button, currently this code doesnt displays anything in the other textfiels. If i put anything, for example "A" instead of "%.Of" it would display the "A" in the textfield but not the average or the sum. Please i need help with a code that would work, dont mind if i need to change a lot.
This is what im working with:
private void jButton_RankingActionPerformed(java.awt.event.ActionEvent evt) {
double R[] = new double [14];
R[0] = Double.parseDouble(jTextField_Math.getText());
R[1]= Double.parseDouble(jTextField_English.getText());
R[2] = Double.parseDouble(jTextField_Spanish.getText());
R[3] = Double.parseDouble(jTextField_Biology.getText());
R[4] = Double.parseDouble(jTextField_Physics.getText());
R[5] = Double.parseDouble(jTextField_Chemestry.getText());
R[6] = Double.parseDouble(jTextField_PE.getText());
R[7] = Double.parseDouble(jTextField_Humanities.getText());
R[8] = Double.parseDouble(jTextField_Technology.getText());
R[9] = (R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8])/ 9;
R[10] = R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8];
String Average = String.format("%.Of",R[9]);
jTextField_Average.setText(Average);
String TotalScore = String.format("%.Of",R[10]);
jTextField_TotalScore.setText(TotalScore);
if(R[10]>=50)
{
jTextField_Ranking.setText("Superior");
}
else if (R[10]>=41){
jTextField_Ranking.setText("Alto");
}
else if (R[10]>=34){
jTextField_Ranking.setText("Basico");
}
else if (R[10]<=33){
jTextField_Ranking.setText("Bajo");
Since you mentioned that an A would print, it follows that jButton_RankingActionPerformed is being called. The issue you have is the format string you are using to print the total and average. You have mistakenly chosen the capital letter O rather than the number zero.
Replace this (which contains a capital letter O):
String.format("%.Of",R[9]);
With
1) No decimal will be printed: i.e. 50.2 would be 50
String.format("%.0f",R[9]);
2) Or perhaps you want to see one decimal place like 50.2
String.format("%.1f",R[9]);
Also a very small optimization is:
R[9] = (R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8])/ 9;
R[10] = R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8];
Could be replaced with:
R[10] = R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8];
R[9] = R[10] / 9;
or use a loop to calculate R[10]. (to add R[0] to R[8])
I got a task. The input of the Java Decathlon program is a CSV-like text file. The task is to output an XML file with all athletes in ascending order of their places, containing all the input data plus total score and the place in the competition (in case of equal scores, athletes must share the places, e.g. 3-4 and 3-4 instead of 3 and 4)
This is my cvs file:
Jana Kari;12.61;5.00;9.22;1.50;60.39;16.43;21.60;2.60;35.81;5.25.72
Eva Narun;13.04;4.53;7.79;1.55;64.72;18.74;24.20;2.40;28.20;6.50.76
Maja Hope;13.75;4.84;10.12;1.50;68.44;19.18;30.85;2.80;33.88;6.22.75
Kirke Kanda;13.43;4.35;8.64;1.50;66.06;19.05;24.89;2.20;33.48;6.51.01
I got these constants for each decathlon event
double[] A = new double[]{25.4347,0.14354,51.39,0.8465,1.53775,5.74352,12.91,0.2797,10.14,0.03768};
double[] B = new double[]{18,220,1.5,75,82,28.5,4,100,7,480};
double[] C = new double[]{1.81,1.4,1.05,1.42,1.81,1.92,1.1,1.35,1.08,1.85};
Formula for points is
Points = INT(A(B — P)^C) for track events (faster time produces a better score)
Points = INT(A(P — B)^C) for field events (greater distance or height produces a better score)
"P" is persons records (from cvs). I dont really understand how to read properly from file that it would allow me to do calculations with numbers only. Should i use two dimensional array for cvs file ? Its very confusing and im stuck.
EDIT
Well i believe for outputing later to xml file one dimensional array is better. The point of my task is code simplicity, but CVS file may be expanded to N lines so i never know how much rows it will have. I want to use number array in this code:
double[] A = new double[]{25.4347,0.14354,51.39,0.8465,1.53775,5.74352,12.91,0.2797,10.14,0.03768};
double[] B = new double[]{18,220,1.5,75,82,28.5,4,100,7,480};
double[] C = new double[]{1.81,1.4,1.05,1.42,1.81,1.92,1.1,1.35,1.08,1.85};
double PTS;
double finalscore;
for (int i = 0; i < P.length;i++ )
{
finalscore=0;
if (i == 0)
{
PTS = A[i]* Math.pow((P[i]-B[i]),C[i]);
}
else if (i == 4)
{
PTS = A[i]* Math.pow((P[i]-B[i]),C[i]);
}
else if (i == 5 || i == 9)
{
PTS = A[i]* Math.pow((P[i]-B[i]),C[i]);
}
else
{
PTS = A[i]* Math.pow((P[i]-B[i]),C[i]);
}
finalscore = finalscore + PTS;
}
System.out.println(finalscore);
}
}
Where P[] would be array first lane of number without name.
P.S it seems code above gives me result NaN when i use
double[] P = new double[]{12.61,5.00,9.22,1.50,60.39,16.43,21.60,2.60,35.81,5.272};
Yes, you have the right idea - you can use a two dimensional array. I would also recommend you create a class called Person, as this is Java programming and Java is object-oriented, but if you have not studied creating multiple classes yet, you can skip that bit and just do it with two arrays, one one-dimensional array for the names and one two-dimensional array for the numbers.
For the one-dimensional array approach
public class Person {
String name;
double[] scores;
int minutes;
int seconds;
int hundredths;
public Person(String line) {
String[] splitted = line.split(";");
name = splitted[0];
// now fill in the other fields
for(int i = 1; i < splitted.length - 1; i++) {
scores[i - 1] = Double.parseDouble(splitted[i]);
}
String times = splitted[splitted.length - 1].split("\\.");
minutes = Integer.parseInt(time[0]);
// etc. - fill in the rest
}
}
(Actually, this might be wrong, because I assumed most of the numbers are scores, but I guess they are really seconds and hundredths of a second. It doesn't really matter, unless you could have a time over one minute for those events.)
Then you need to have an array of Person objects in your other class - let's make it quite big so that it will be big enough hopefully:
Person[] array = new Person[10000];
Now have a loop, and whenever you read a line from the file you just call the constructor.
array[j] = new Person(line);
Nice approach, isn't it?
Looks like this is the week for this type of question. And after reading through all of the new ones and several old ones, I'm no less confused!
I have a text file with 5 employees, each having 10 salary values listed beneath their name. I am to read in this file, find and display the employee Name, minimum salary, maximum salary and the average salary for each person. I must have 3 loops: One to control reading the file, one to lad the data into the array, and one to do the calculations. I have to print the information for each person on one line, and i must allow decimals rounded to 2 decimal places apparently using Math.round which I've never heard of!
I am embarrassed to show you the mess of code I have because it's not much, but I don't know after reading all that I have if I've even started correctly. I do not know if I have even the right idea of how to proceed. Your help is appreciated.
UPDATED CODE: AGAIN!
import javax.swing.*;
import java.io.*;
public class MinMaxSalary3
{
public static void main(String args[])throws Exception
{
// Declare input file to be opened.
FileReader fr = new FileReader ("salary.dat");
BufferedReader br = new BufferedReader (fr);
//General Declarations
final String TITLE = "Employee's Salary Report";
String employeeName, salaryString;
double avgSalary=0.0;
double totalSalary = 0.0;
double sum = 0.0;
// Declare Named Constant for Array.
final int MAX_SAL = 10;
// Declare array here.
int salary[] = new int[MAX_SAL];
System.out.println (TITLE);
while ((employeeName = br.readLine()) != null)
{
System.out.print ("" + employeeName);
// Use this integer variable as your loop index.
int loopIndex;
// Assign the first element in the array to be the minimum and the maximum.
double minSalary = salary[1];
double maxSalary = salary[1];
// Start out your total with the value of the first element in the array.
sum = salary[1];
// Write a loop here to access array values starting with number[1]
for (loopIndex = 1; loopIndex < MAX_SAL ;loopIndex++)
// Within the loop test for minimum and maximum salaries.
{
if (salary[loopIndex] < minSalary)
{
minSalary = salary[loopIndex];
if (salary[loopIndex] > maxSalary)
maxSalary = salary[loopIndex];
}
{
// Also accumulate a total of all salaries.
sum += sum;
// Calculate the average of the 10 salaries.
avgSalary = sum/MAX_SAL;
}
// I know I need to close the files, and end the while loop and any other loops. I just can't think that far right now.
}
{
// Print the maximum salary, minimum salary, and average salary.
System.out.println ("Max Salary" + maxSalary);
System.out.println ("Min Salary" + minSalary);
System.out.println ("Avg Salary" + avgSalary);
}
System.exit(0);
}
}
}
I must have 3 loops: One to control reading the file, one to lad the
data into the array, and one to do the calculations.
What I've written below might just be more gobbledygook to you now, but if you ever get past this class it might be useful to know.
Another way to look at this would be more object-oriented and better decomposition to boot: You need an object to hold the data, to perform the calculations, and render output. How you get that data is immaterial. It's files today; next time it might be HTTP requests.
Start with an Employee object. I deliberately left out a lot of detail that you'll have to fill in and figure out:
package model;
public class Employee {
private String name;
private double [] salaries;
public Employee(String name, int numSalaries) {
this.name = name;
this.salaries = new double[numSalaries];
}
public double getMinSalary() {
double minSalary = Double.MAX_VALUE;
// you fill this in.
return minSalary;
};
public double getMaxSalary() {
double maxSalary = Double.MIN_VALUE;
// you fill this in.
return maxSalary;
}
public double getAveSalary() {
public aveSalary = 0.0;
if (this.salaries.length > 0) {
// you fill this in.
}
return aveSalary;
}
}
The beauty of this approach is that you can test it separately, without worrying about all the nonsense about file I/O. Get this object right, put it aside, and then tackle the next piece. Eventually you'll have a clean solution when you assemble all these smaller pieces together.
Test it without file I/O using JUnit:
package model;
public class EmployeeTest {
#Test
public void testGetters() {
double [] salaries = { 10000.0, 20000.0, 30000.0, 40000.0 };
Employee testEmployee = new Employee("John Q. Test", salaries);
Assert.assertEquals("John Q. Test", testEmployee.getName());
Assert.assertEquals(10000.0, testEmployee.getMinSalary(), 1.0e-3);
Assert.assertEquals(40000.0, testEmployee.getMaxSalary(), 1.0e-3);
Assert.assertEquals(25000.0, testEmployee.getMinSalary(), 1.0e-3);
}
}
The approach you would want to espouse in this situation is an object-oriented approach. Bear in mind that objects are a representation of related data. Consider that an Employee may have information about their salary, name, and what department they work in (as an example).
But that's just one Employee. You may have hundreds.
Consider creating a model of an Employee. Define what is most pertinent to one of them. For example, they all have to have a name, and have to have a salary.
One would then elect to handle the logic of finding information about the collection of Employees - including min, max, and average salaries - outside of the scope of the generic Employee object.
The idea is this:
An Employee knows everything about itself.
The onus is on the developer to tie multiple Employees together.
It's possible that I don't know enough about what your problem is specifically looking for - I'm not even sure that you can use objects, which would really suck - but this is definitely a start.
As for your compilation errors:
salary is a double[]. An array holds many different values of type double inside of it, but a double[] isn't directly a double. Assigning a non-array type to an array type doesn't work, from both a technical stance, and a semantic stance - you're taking something that can hold many values and trying to assign it to a container that can hold one value.
From your code sample, you want to use a loop (with a loop variable i) to iterate over all elements in salary, and assign them some value. Using just salary[0] only modifies the first element.