I have some code like this:
void drawPlot()
{
String[] dataItemPrices = loadStrings("itemPrices.csv"); //load in .csv file, store as string array
itemName = new String[dataItemPrices.length-1];
itemPrice = new float[dataItemPrices.length-1];
for (int i=0; i<dataItemPrices.length-1; i++)
{
//split array to consider commas
String[] tokensItemPrices = dataItemPrices[i+1].split(",");
itemName[i] = tokensItemPrices[0];
itemPrice[i] = Float.parseFloat(tokensItemPrices[1]);
dataMin = min(dataMin,itemPrice[i]);
dataMax = max(dataMax,itemPrice[i]);
itemPriceScaled = new float[map(itemPrice[i], dataMin, dataMax,
0, (height-100))];
}
}
The last line of code is causing problems, when I compile I get "cannot convert from float to int".
The only int is the [i] but that's used to access an array, it can't be that can it? Otherwise how can I access the array?
Help please!
Thanks!
There are a few possible alternatives:
You are creating a new float array and you need an int size for it, does map return a float? If this is the case, map could need major modifications.
What kind of parameters does map need? itemPrice[i], dataMin and dataMax are all floats(height could be too), is this correct? In this case, a cast to (int) could be enough or your function prototype needs to be fixed...
Please add the code for map and all variables declarations to your question.
Edit:
After your comment and looking at your code, maybe this is what you want to do: populating an array with prices (taken from the itemPrice array) "scaled" using map that has obviously the same size as the other two arrays:
void drawPlot()
{
String[] dataItemPrices = loadStrings("itemPrices.csv"); //load in .csv file, store as string array
itemName = new String[dataItemPrices.length-1];
itemPrice = new float[dataItemPrices.length-1];
itemPriceScaled = new float[dataItemPrices.length-1]; // <<<<<Added
for (int i=0; i<dataItemPrices.length-1; i++)
{
//split array to consider commas
String[] tokensItemPrices = dataItemPrices[i+1].split(",");
itemName[i] = tokensItemPrices[0];
itemPrice[i] = Float.parseFloat(tokensItemPrices[1]);
dataMin = min(dataMin,itemPrice[i]);
dataMax = max(dataMax,itemPrice[i]);
itemPriceScaled[i] = map(itemPrice[i], dataMin, dataMax,
0, (height-100)); //<<<Modified
}
}
Related
First off, sorry for the terrible title I don't know how to describe this well. I have a sql file with a table with two columns (number and price), in java im extracting the data and have stored them into two seperate lists. Some of the numbers in the column are the same eg (100, 100, 101) and correlate to a different price eg (50, 40, 60). I need to find a way to add all the prices together that have the same column value, so an output like (90, 60). The lists are in order so index one of my list named number will go with index one of my list named price. A small example of the lists would be:
ArrayList<String> number = new ArrayList<String>();
ArrayList<Integer> price = new ArrayList<Integer>();
number.add("100");
number.add("100");
number.add("101");
number.add("101");
number.add("101");
number.add("102");
number.add("103");
number.add("103");
price.add(50);
price.add(150);
price.add(20);
price.add(200);
price.add(75);
price.add(40);
price.add(100);
price.add(125);
Any help would be appreciated, Thanks.
You could use a HashMap<String, Integer>.
Assuming that the size of number and price is the same. You can do something like this:
HashMap<String, Integer> sumForNumber = new HashMap<>();
for (int i = 0; i < number.size(); i++) {
String key = number.get(i);
sumForNumber.put(key, sumForNumber.getOrDefault(key, 0) + price.get(i));
}
I hope this code helps you
Map<String, Integer> result = new HashMap<>();
for (int i = 0; i < number.size(); i++) {
String num = number.get(i);
if (result.containsKey(num)) {
Integer sum = result.get(num);
result.put(num, sum + price.get(i));
} else {
result.put(num, price.get(i));
}
}
Im using MPandroid chart to inflate Pie Chart, with some String JSON return
i tried to cast String value with float.parseFloat("3584907054456.48")
but it had exponent value when i log it, something like this 3584907E12
i need to get float value 3584907054456.48
is it possible ?
List<String> dataStackedSalesVolume1;
List<String> dataStackedSalesVolume2;
float[] firstDataStacked = new float[counte];
float[] secondDataStacked = new float[counte];
int counte = merchantECommerceDataAll.getData().getMerchantECommerceTipekartuList().getMerchantECommerceTipeKartuData().get(1).getDataSalesVolume().size();
dataStackedSalesVolume1 = merchantECommerceDataAll.getData().getMerchantECommerceTipekartuList().getMerchantECommerceTipeKartuData().get(0).getDataSalesVolume();
dataStackedSalesVolume2 = merchantECommerceDataAll.getData().getMerchantECommerceTipekartuList().getMerchantECommerceTipeKartuData().get(1).getDataSalesVolume();
for (int i=0; i< counte; i++) {
firstDataStacked[i] = Float.parseFloat(dataStackedSalesVolume1.get(i));
secondDataStacked[i] = Float.parseFloat(dataStackedSalesVolume2.get(i));
}
i tried to get the string and put it into new list and then parse that list and put parsed value into float[]
but it the results is rounded, i need to get the full length of data without rounded
Edit - The BigDecimal value can be converted to float value by using the floatValue() method. (Example - float requiredValue = bigDecimalValue.floatValue();)
Do note however that this will result in a drop in precision.
BigDecimal bigDecimalValue = new BigDecimal("3584907054456.48");
System.out.println(bigDecimalValue); //3584907054456.48
float floatValue = bigDecimalValue.floatValue();
System.out.println(floatValue); //3.58490702E12
//Formatted better to show the drop in precision.
System.out.println(String.format("%.2f", floatValue)); //3584907018240.00
Don't use float, use BigDecimal instead.
Do note that you won't be directly able to use operators such as +,-,*,etc. You'll have to use the provided methods, refer to the official documentation or an article such GeeksForGeeks articles to help you get an initial hang of it.
Sample code -
List<String> dataStackedSalesVolume1;
List<String> dataStackedSalesVolume2;
BigDecimal[] firstDataStacked = new BigDecimal[counte];
BigDecimal[] secondDataStacked = new BigDecimal[counte];
int counte = merchantECommerceDataAll.getData().getMerchantECommerceTipekartuList().getMerchantECommerceTipeKartuData().get(1).getDataSalesVolume().size();
dataStackedSalesVolume1 = merchantECommerceDataAll.getData().getMerchantECommerceTipekartuList().getMerchantECommerceTipeKartuData().get(0).getDataSalesVolume();
dataStackedSalesVolume2 = merchantECommerceDataAll.getData().getMerchantECommerceTipekartuList().getMerchantECommerceTipeKartuData().get(1).getDataSalesVolume();
for (int i=0; i< counte; i++) {
firstDataStacked[i] = new BigDecimal(dataStackedSalesVolume1.get(i));
secondDataStacked[i] = new BigDecimal(dataStackedSalesVolume2.get(i));
}
You can use something like BigDecimal.valueOf(new Double("3584907054456.48")) from java.math
After this you can divide, compare your value and so on
I am trying to add a sequence of letters as Strings to a 2D array. So object [17] goes to endState[0][0]; [18] to endState[0][1] and so forth.
The problem I have is with the outside for loop, which just adds object at [32] to all of the cells in the matrix. Normally I would use an iterator to deal with this when using other collections, however, it is not possible with arrays as far as i am aware (I am a novice as you may have guessed).
String [][] endState = new String[4][4];
for(int i1=17;i1<33;i1++){
for(int r=0;r<endState.length;r++){
for(int c=0;c<endState.length;c++){
endState[r][c] = config.split("")[i1];
}
}
}
Any suggestions on how I can overcome this?
Many thanks.
Do you need something like that ?
String[] configs = config.split("");
String [][] endState = new String[4][4];
int i = 17;
for(int r=0;r<endState.length;r++){
for(int c=0;c<endState.length;c++){
endState[r][c] = configs[i++];
}
}
If you want to turn the letters into a gird you can do.
String[] letters = config.substring(17).split("");
String[][] endState = new String[4][];
for (int i = 0; i < endState.length; i++)
endState[i] = Arrays.copyOf(letters, i * 4, 4);
or you could do
String[][] endState = IntStream.range(0, 4)
.mapToObject(i -> Arrays.copyOf(letters, i * 4, 4))
.toArray(s -> new String[s][]);
If you use Java 8, you can do it as follows:
Arrays.asList(someArray).foreach(item -> {});
or
Arrays.asList(someArray).stream().ANY_STREAM_FUNCTION_HERE
If you want iterate your 2dim array:
Arrays.asList(someArray).foreach(item -> {
Arrays.asList(item).foreach(item2 -> {[Do your job here]})
});
You can do it more Java 7 way:
for(item : Arrays.asList(someArray)) {
...
}
Anyway you can always use Arrays.asList(someArray) to obtain a list from array.
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.
I have a method that requires a String[] for some details but after putting these details in how do I get them out one by one?
new String[] otherDetails = {"100", "100", "This is a picture"};
now in the picture I want to set the first string as the height, the second as the width, and the third as a description.
You refer to an element of an array by its index, like this:
height = otherDetails[0]; // 100
width = otherDetails[1]; // 100
description = otherDetails[2]; // This is a picture
You use the index to get the values
height = otherDetails[0];
width = otherDetails[1];
description = otherDetails[2];
Extract The details from array as follows :
height = otherDetails[0]; // 100
width = otherDetails[1]; // 100
description = otherDetails[2]; // This is a picture
Then call your method MyFunction(String heigth,String width,String description);
The index comments are probably what you're looking for, but you can also iterate through the elements using a loop.
int arraySize = stringArray.length;
for(int i=0; i<arraySize; i++){
if(i==0)
height = stringArray[i]; //do stuff with that index
}
This isn't the "right" approach for your particular problem, but I think it might help you understand ways that you can access items inside an array.
Side note, you could use alternative syntax:
String[] array = new String[3];
//fill in array
for(String s : array){
//this cycles through each element which is available as "s"
}