Passing double values into 2D Array - java

I'm trying to initialize my 2D array in java by passing specific double values into it, but I'm returning an error " ']' expected".
double[][] EnglishToFrenchProb = new double[2][3];
double[0][0] = 0.0; //unused
double[0][1] = 0.08;
double[0][2] = 0.06;
double[1][0] = 0; //unused
double[1][1] = 0.08;
double[1][2] = 0.06;
What am I doing wrong, and I realise there's an easier way to pass values into 2D arrays but this is the only way I could think where I can index them easily by their own values (which I need to do)

To set some value you have use variable's name:
EnglishToFrenchProb[0][0] = 0.00;
You can use also following syntax:
double[][] EnglishToFrenchProb = {{0.00, 0.08, 0.06}, {0.00, 0.08, 0.06}};

You need to refer to variable name:
double[][] EnglishToFrenchProb = new double[2][3];
EnglishToFrenchProb[0][0] = 0.0; //and so forth

Related

Convert String to Float with Large Number

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

How to convert double values to string in a text field

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])

Cannot convert from float to int

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
}
}

Multidata Type Array In Java

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.

How can I store a bunch of double in a single double?

I edited my post.
:: New logic problem, everytime I input only 1 integer the += only prints 0.
System.out.print("\nEnter the property code: ");
sPropertyCode = input.next();
bError = false; //set to false
dTotalCommission += dCommissionRate;
dTotalSales += dSellPrice;
if (sPropertyCode.equalsIgnoreCase("R"))//if r or R dRate will store 7,...perform calculation for dCommissionRate
{
dRate = 7;
dCommissionRate = dSellPrice * (dRate/100);
System.out.print("Total commission on this property is $" +dCommissionRate);
} //this works and prints the calculated amount of rate but when it is going to the last line....
if (sYesOrNo.equalsIgnoreCase("n"))
{
System.out.println(sApplicationReport);//prints the Summary Report
System.out.println ("----------------------------------------------------------");
System.out.println ("Total property sales: $" + dTotalSales);//all the stored values for dSellPrice will be added and printed
System.out.println("Total Commissions: $"+ dTotalCommission);//This part only prints 0.00 instead of the calcuated dCommissionRate
break;
}
dTotalPrice += dSellPrice
means : dTotalPrice = dTotalPrice + dSellPrice
But if you want to store 10000 and 20000 in a single variable , you can use an arrayList :
Example :
ArrayList<Double> myValues = new ArrayList<Double>();
myValues.add(10000 );
myValues.add(200O00 );
// etc.
If you want to show them :
for(int i = 0 ; i < myValues.size(); i++){
Double mySingleValue = myValues.get(i);
System.out.println(mySingleValue.toString());
}
Hm. It's kind of hard to follow your thinking, but here is my best shot.
Your code here (dTotalPrice += dSellPrice) Will add the value of dSellPrice to dTotalPrice.
aside from a semicolon you aren't missing anything.
Instead of trying to store multiple doubles in a single double variable, why not try and store your multiple doubles in an array? Therefore you could store your multiple number values in this array and then pick out the ones you want.
You'd just reassign the variable. No problem.
Try it!
double dada = 10.7;
/* run jump play */
dada = 3.141592653589;
However, what makes more sense is to use an array.
declare a double array -
double[] myNumbers = {28.3, 21.2};

Categories