I have the problem that in my program I have 4 annotated combo boxes and 2 of them return a number but in String type, which I need to store in a floating type variable, My combo box is called combo2 and
jComboBox4, the 2 variables that you see are the ones in which I need to store the data but I need to convert them. I would appreciate your help. Greetings.
//My combobox is combo2 and jComboBox4
// I need save in this variables
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
int numeroextra1;
int numeroextra2;
}
You can convert string variable to float as following:
string s = "123.45";
float f = Float.parseFloat(s);
You can use following methods:
String s = "10.01";
Float fObject = Float.valueOf(s);//get Float object
float fNumber = Float.parseFloat(s);//get float number
Related
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 have a project and my Java program in Swing uses a double array to accept values from the user and print the total of the items, kind of like an order form.
Say the user enters no value in the text box, this shows an error and prevents further calculations.
My question is ,what should I code in order for the computer to understand that there is nothing entered in the text box , so just take the value as 0. I want to either do this by comparing/converting the double array value to a string and then continuing with calculations .
Here is my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
double price[]=new double[]{0.25,8.55,0.50,0.25};
double amount[]=new double[4];
double quantity[]=new double[4];
quantity[0]=Double.parseDouble(jTextField1.getText());
quantity[1]=Double.parseDouble(jTextField2.getText());
quantity[2]=Double.parseDouble(jTextField3.getText());
quantity[3]=Double.parseDouble(jTextField4.getText());
for(int i=0;i<4;i++) // I want to use a for-loop or if-statement to
check if there is a value entered or not
{
if()
{
quantity[i] //no clue what to do here.
}
}
for(int i=0;i<4;i++)
{
{
amount[i]=quantity[i]*price[i];
}
}
jTextField5.setText(String.valueOf(amount[0]));
jTextField6.setText(String.valueOf(amount[1]));
jTextField7.setText(String.valueOf(amount[2]));
jTextField8.setText(String.valueOf(amount[3]));
First you would want to check if the text fields are empty or a String value before parsing them. And you will likely need to do it for all of the fields.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// check the values of the text fields including an or condition for regular expressions
if (jTextField1.isEmpty() || jTextField1.getText().matches("\\d+.?\\d*") {
// you can use something like a modal to alert
JOptionPane.showMessage(null,"Must enter a decimal value");
} else {
// do something with jTextField1
}
}
You can use
if (!jTextField1.getText().isEmpty())
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 want a placeholder value to hold the answer to a calculation, however the compiler doesn't like it.
Here is my code..
float valueOne = Float.parseFloat(txtOne.getText());
float valueTwo = Float.parseFloat(txtTwo.getText());
float valueThree = Float.parseFloat(txtThree.getText());
float final = valueOne+valueTwo+valueThree; // this line is bringing errors
Would really appreciate it if you could help me out.
Your problem is that final is a reserved keyword in Java. You cannot use it as a variable name. Just rename your last variable to something like finalValue and it will compile fine.
float valueOne = Float.parseFloat(txtOne.getText());
float valueTwo = Float.parseFloat(txtTwo.getText());
float valueThree = Float.parseFloat(txtThree.getText());
float finalValue = valueOne+valueTwo+valueThree;
Here is a list of keywords in Java.
final is a keyword. Try changing your float final to another name like float finalAnswer
It is because you use the keyword final.
Change your name
float valueOne = Float.parseFloat(txtOne.getText());
float valueTwo = Float.parseFloat(txtTwo.getText());
float valueThree = Float.parseFloat(txtThree.getText());
float finalHolder = valueOne+valueTwo+valueThree; // No more errors
final is a reserved keyword in java you can not use it as variable name.
If I had a JFormattedTextField like this
MaskFormatter formatter = new MaskFormatter("#,#");
JFormattedTextField textField = new JFormattedTextField(formatter);
and if I had variables
int x = 0;
int y = 0;
how can I store the first number in the textfield to x, and the second number to y?
Assuming the first & second numbers are those either side of the comma , in the JFormattedTextField, you could do:
String[] numbers = textField.getText().split(",");
int x = Integer.parseInt(numbers[0]);
int y = Integer.parseInt(numbers[1]);
The mask does not change how the inner value is stored, it just tells how to represent/input it.
So you still have a .getText() which returns a String in the format of your election. Process that String (split(), StringTokenizer) as you see fit.