Multicast array of types in Java
Complete newbie here guys. I am working on a Java program to prompt the user for 3 variables that are used to calculate the future value of an investment. Everything works great except when it's time to put both of my datatypes in ONE array.
Here's what SHOULD should look like:
Year Future Value
1 $1093.80
2 $1196.41
3 $1308.65
...
It looks like this:
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 is double (rounded). I've sat here racking my brain and all the forums I can find and have no success. Every time I put both values into an array, I get a message about the concatenation of two different data types. Any insight would be greatly appreciated. Below is the code for my complete 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;
}
}
source to share
One solution is to start by implementing the function pad
. 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();
}
We can now combine this with String.format()
to get dollars and cents, use 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);
}
source to share
The System.out.println command is not the only way 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 like this to accommodate your headers.
PS - I'm sure it's just a matter of formatting the output - you don't want all of these values to be put into one array, right?
Given that you are really looking for formatted output, it might be better to use the printf () method.
The following inside the loop (instead of the three lines I wrote above) should do the trick (untested - I haven't used printf () format lines for a long, long time).
System.out.printf("%i\t$%0.2f", y, f);
source to share
EDIT: Edited to answer your question in the comments about constructors ... You should also check this for further understanding
You can create a class that will contain both arrays ... This will give you one object, let it StockData
, which contains two arrays for the two different 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 your 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 can also have an object that will hold values double
and int
so the object will represent a single stock information of 2 values, 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);
source to share
An interesting data structure you could use here is Map (more specifically in Java, HashMap). What you are doing is binding one value to another, integer to double, so you can do something similar to this:
Map<Integer, Double> myMap = new HashMap<>();
This will take a year as an integer and a double as a price value, and you can iterate over the map to print each value.
Also, if you're really looking for an "array of arrays of multiple types", Java automatically converts from integer to double if you need to. For example:
int i = 2;
double[] arr = new double[2];
arr[0] = 3.14
arr[1] = i;
The above code is absolutely correct.
source to share
If you want the program to have a specific format, you could try changing your code and putting it where yours 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 get your result in the format you want without using arrays. But if you want to make an array for this, you can 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 uppercase, this should be InvestmentValue
I hope this helps you
source to share