how to compare a Double Value in if statement in java? - java

I have a desktop application with textboxs that contain a price values. As an example if i input 25000
Double priceSec = Double.parseDouble(cusPrice.getText());
i'm passing that 25000 as a double value
so now i want to compare that value and check whether it is empty or not?
if(cusPrice2.getText()==null || cusPrice2.getText().isEmpty()){
Double priceSec=0.0;
}
i know i can create an else condition for
if textbox !=null
total=txtbox1+txtbox2+txtbox3;
if textbox value is empty or not empty. value should be there in total.
but in my code ,it displays as null.
Do i have any other way to do that?
can you tell me a way to do that.
here is my full code
private void cusOkBtnActionPerformed(java.awt.event.ActionEvent evt) {
Double priceSec = Double.parseDouble(cusPrice2.getText());
Double priceThird = Double.parseDouble(cusPrice3.getText());
Double priceFourth = Double.parseDouble(cusPrice4.getText());
Double priceFifth = Double.parseDouble(cusPrice5.getText());
if(cusPrice2.getText()==null || cusPrice2.getText().isEmpty() || cusPrice2.getText() !=null ){
priceSec=0.0;
costCls.setItemPrice(priceSec);
}
else if(cusPrice3.getText()==null || cusPrice3.getText().isEmpty()){
priceThird=0.0;
}
else if(cusPrice4.getText()==null || cusPrice4.getText().isEmpty()){
priceFourth=0.0;
}
else if(cusPrice5.getText()==null || cusPrice5.getText().isEmpty()){
priceFifth=0.0;
}
Double setItemTotal = priceCus+priceSec+priceThird+priceFourth+priceFifth;
}

You should rather use Exceptions.
try {
Double priceSec = Double.parseDouble(cusPrice.getText());
} catch (NullPointerException e1) {
//null somewhere
} catch (NumberFormatException e2) {
//not a number - on controlled input - empty field.
}

double is the primitive type for floating point, Double is the Object child that wraps a double value. So:
double priceSec = Double.parseDouble(cusPrice.getText());
double price2Sec = cusPrice2.getText().isEmpty())
? 0.0
: Double.parseDouble(cusPrice.getText());
if (priceSec == price2Sec) { ...
However for financial data a double has small approximation errors, that can become visible - especially with ==. Hence one might better use BigDecimal, which does fixed point arithmetic.
BigDecimal priceSec = new BigDecimal(cusPrice.getText());
if (priceSec.compareTo(price2Sec) == 0) { ...
With a bit ugly API doing calculations:
x = x.add(y.divide(new BigDecimal("12.50")));

you can try this
private void cusOkBtnActionPerformed(java.awt.event.ActionEvent evt) {
Double priceSec=0.0,priceThird=0.0,priceFourth=0.0,priceFifth=0.0;
costCls.setItemPrice(0.0);
if(cusPrice2.getText()!=null && !cusPrice2.getText().isEmpty() ){
priceSec = Double.parseDouble(cusPrice2.getText());
costCls.setItemPrice(priceSec);
}
else if(cusPrice3.getText()!=null && !cusPrice3.getText().isEmpty()){
priceThird = Double.parseDouble(cusPrice3.getText());
}
else if(cusPrice4.getText()!=null && !cusPrice4.getText().isEmpty()){
priceFourth = Double.parseDouble(cusPrice4.getText());
}
else if(cusPrice5.getText()!=null && !cusPrice5.getText().isEmpty()){
priceFifth = Double.parseDouble(cusPrice5.getText());
}
Double setItemTotal = priceCus+priceSec+priceThird+priceFourth+priceFifth;
}

It is better to use the built-in Exception semantics already available within the Double.parseDouble(String s) implementation. (IMHO: Don't check up-front as you are making the exceptional-situation part of the normal flow)
Use a function like
private static double getValue(String str) {
try {
return Double.parseDouble(str);
} catch (NumberFormatException e) {
return 0d;
}
}
You would then use it like:
String priceStr = cusPrice.getText();
double d = getValue(priceStr);

Related

Determine the most fitting numeric variable type for a String

I'm trying to create Predicates to test Strings and determine the most appropriate variable type, which means I want to get the "smallest" numeric variable type that the parsed String fits into.
So for example, for a String "-1.2" the detected type should be float, but if the number exceeds the float range, it should detect double. If the number is even bigger, then BigDecimal.
For non-floating point numbers my tests seem to work fine,
but the decimal numbers are giving me more headaches than they should.
This is my isFloat test:
Predicate<String> isFloat =
s -> {
try {
Double d = Double.parseDouble(s);
return d >= -Float.MAX_VALUE && d <= Float.MAX_VALUE;
} catch (Exception e) {
return false;
}
};
String minOfFloat = String.valueOf(-Float.MAX_VALUE);
System.out.println(minOfFloat);
System.out.println(Double.parseDouble(minOfFloat));
System.out.println(isFloat.test(minOfFloat));
Outputs:
-3.4028235E38
-3.4028235E38
false //WHYYYYY
Similarly my next test would be to check if the number fits a double, and if not, return "BigDecimal".
What's the correct way to test this?
EDIT: This is the way I'm doing it, accepted answer brought me there:
public static final Predicate<String> isFloat =
s -> {
try {
Double d = Double.parseDouble(s);
return d.floatValue() >= -Float.MAX_VALUE
&& d.floatValue() <= Float.MAX_VALUE
&& !Float.isInfinite(d.floatValue())
&& !Float.isNaN(d.floatValue());
} catch (Exception e) {
return false;
}
};
Change your predicate to compare with d.floatValue() >= -Float.MAX_VALUE && d <= Float.MAX_VALUE;
In case, if your double value exceeds float range d.floatValue() returns infinity so you should be good with the change
Predicate<String> isFloat = s -> {
try {
Double d = Double.parseDouble(s);
return d.floatValue() >= -Float.MAX_VALUE && d <= Float.MAX_VALUE;
} catch (Exception e) {
return false;
}
};
String maxDouble = String.valueOf(Double.MAX_VALUE);
System.out.println(maxDouble);
System.out.println(isFloat.test(maxDouble));
Using BigDecimal is recomended when widening primitive conversion will be applied. I couldn't find a good duplicate, but see this posts
how-to-compare-correctly-long-and-float-primitives
comparing-float-and-double-primitives-in-java
to understand why you might get wrong results when comparing two different types. So I would do something like:
Predicate<String> isFloat =
str -> new BigDecimal(str).compareTo(new BigDecimal(String.valueOf(Float.MAX_VALUE))) <= 0 &&
new BigDecimal(str).compareTo(new BigDecimal(String.valueOf(-Float.MAX_VALUE))) >= 0;

Java FX arithmetic expression in a button

hi i want to do a button that takes two input fields and trying to do the following :
chick if it's a number .(so it can devide the two numbers)
i can't devide any number by zero .
and showing that it's a arithmetic expression .
so any help ?
the code is blow ::
enter image description here
code ::
b4.setOnMouseClicked((MouseEvent ex) -> {
String Num1 = tf4.getText();
String Num2 = tf8.getText();
if(Num1.matches("^\\d+(\\.\\d+)?") && Num2.matches("^\\d+(\\.\\d+)?")) {
try {
double Num1f = Double.parseDouble(Num1);
double Num2f = Double.parseDouble(Num2);
double result =(Num2f / Num1f);
valf4.setText(String.valueOf(result));
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException");
valf4.setText("You can't do that !");
}
} else {
}
});
and it show infinity
not what i expected as i did in catch area
Floating point arithmetic in Java does not throw exceptions for division by zero; it evaluates to one of the special values in the Double class (Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY).
Instead of catching the exception, you can just test if the denominator is zero, or test if the result is infinite:
b4.setOnMouseClicked((MouseEvent ex) -> {
String num1 = tf4.getText();
String num2 = tf8.getText();
if(num1.matches("^\\d+(\\.\\d+)?") && num2.matches("^\\d+(\\.\\d+)?")) {
double num1f = Double.parseDouble(num1);
double num2f = Double.parseDouble(num2);
double result = num2f / num1f;
if (Double.isInfinite(result)) {
valf4.setText("You can't do that !");
} else {
valf4.setText(String.valueOf(result));
}
} else {
}
});

Problem with getting data to go into an array

So for this program, the mean and median are supposed to calculated and displayed but I do not think the data I am inputting is getting put into the array because it runs without error but does not display any data I have put into it.
public static double Mean(double[] gradeArray, int numGrades) {
double totalArray = 0.0;
double mean;
for (int i = 0; i < numGrades; i++) {
totalArray = gradeArray[i] + totalArray;
}
mean = totalArray / numGrades;
return mean;
}
public static double Median(double[] gradeArray, int numGrades) {
double median;
Arrays.sort(gradeArray, 0, numGrades);
if (numGrades % 2 == 0) {
median = ((gradeArray[(numGrades / 2)] + gradeArray[(numGrades / 2 + 1)]) / 2);
} else {
median = gradeArray[(numGrades / 2)];
}
return median;
}
private void Enter_Grades_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
double[] totalArray = new double[25];
String text_box_input_str = null;
double text_box_input_num = 0;
int numGrades = 0;
String num_grades_str;
DecimalFormat df = new DecimalFormat("#0.0##");
do {
try {
text_box_input_str = JOptionPane.showInputDialog(null, "Enter Item Price", "Enter Price", JOptionPane.PLAIN_MESSAGE);
if (text_box_input_str == null || text_box_input_str.isEmpty()) {
return;
}
if (text_box_input_num > 0) {
double[] gradeArray = null;
gradeArray[numGrades] = text_box_input_num;
numGrades++;
num_grades_str = Integer.toString(numGrades);
num_grades_text.setText(num_grades_str);
Mean_Text.setText(df.format(Mean(gradeArray, numGrades)));
Median_Text.setText(df.format(Median(gradeArray, numGrades)));
}
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught");
JOptionPane.showMessageDialog(null, "You Must Input numeric data!", "Bad Data!", JOptionPane.ERROR_MESSAGE);
}
} while (text_box_input_str != null && !text_box_input_str.isEmpty());
}
I expect the program to calculate the data that is inputted and calculate the mean and median and then display the totals
it looks like text_box_input_num is set to 0, never updated, but then there is an if check if it's > 0
Rather than pointing out the problem with your code directly, I'll give some pointers on how to find it yourself.
break your code down into smaller parts
for each part, write both the method and the tests that prove the method does what you expect
once the individual parts are working, write the method (and tests) that use them.
You'll end up with several methods with names like getValues, hasValue, printError, checkValidValue, showMedian etc. all of which do exactly what you want.
I guarantee that if you do that it'll become pretty clear very quickly what's wrong.

Checking for proper decimal format Java

I am creating a budget program in java and need to check to see if the user inputs a valid dollar amount, specifically 2 decimal places. There is no specification on how this should be done.
This is my current attempt but the logic is wrong
aExpense5.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String desc = aExpense3.getText();
String value = aExpense4.getText();
double fValue = 0;
try
{
fValue = Double.valueOf(value);
}
catch (NumberFormatException d)
{
JOptionPane.showMessageDialog(null, "Invalid Number1");
}
double dValue = (fValue * 10) % 10;
if (dValue <= 0)
{
updateExpenseList(desc, fValue);
}
else
{
JOptionPane.showMessageDialog(null,"invalid Number");
}
}
});
You can use regex:
if (value.matches("\\d*\\.\\d\\d")) {
// the number string has two decimal places
}
This regex allows for optional whole number part, ".05" would match.
Try something like:
if (fValue*100 == (int)(fValue*100)) {
//fValue had 2 decimal places or less
}
If fValue = 0.11 then fValue*100 = 11. So you'd have 11 == (int)11 which is true.
If fValue = 0.111 then fValue*100 = 11.1. So you'd have 11.1 == (int)11.1 which is false.

Validating int and float value all together

I am getting a value named amount in an object through its getter as shown below.
Let's say the object is h then
h.getAmount()
Now I need to develop a validator that will validate that amount should be of type integer and if it is not then it will throw the exception, I have developed that also as shown below
private boolean isint (String amount){
boolean isValid = true;
try {
Integer.parseInt(amount);
}
catch(NumberFormatException e){
isValid = false;
}
return isValid;
}
Now the issue is that amount coming from h is an integer such as 1234, but it can also be a float such as 1258.26. So in the case of float it throws a NumberFormatException.
How could I make it perfect for both the values whether it is integer or whether it is float?
You could use a regex like this:-
if (str.matches("[-+]?[0-9]*\\.?[0-9]+")) { // You can use the `\\d` instead of `0-9` too!
// Is a number - int, float, double
}
[-+]? - For the sign.
[0-9]*\.?[0-9]+ - For the numbers and the decimal point between them.
Update:-
In case exponential needs to be handled too, then the below regex can be used.
String regex = "[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?";
First of all, if you have a function called isInt it should do exactly that -- check if it's an integer. No more and no less.
You could try something like that
enum VarType {
INTEGER, FLOAT, STRING, EMPTY
}
private VarType getVarType(String amount){
if (amount.length() ==0) {
return VarType.EMPTY;
}
if (amount.contains(".")) {
try {
Float.parseFloat(amount);
}
catch(NumberFormatException e){
return ValType.STRING;
}
return ValType.FLOAT;
} else {
try {
Integer.parseInt(amount);
}
catch(NumberFormatException e){
return ValType.STRING;
}
return ValType.INTEGER;
}
}
I would not recommend it though, because using exceptions in this way is really expensive. Exceptions should be used as their name suggests, to handle special cases, exceptions, and not as a standard flow.
I would do it like this:
public class ParseVarTest {
static enum VarType {
INTEGER, FLOAT, STRING, EMPTY
}
private static VarType getVarType(String amount){
boolean onlyDigits = true;
int dotCount = 0;
if (amount == null) {
return VarType.EMPTY;
}
String trimmed = amount.trim();
if (trimmed.length() == 0) {
return VarType.EMPTY;
}
int a=0;
if (trimmed.charAt(0) == '-') {
a++;
}
for (int max=trimmed.length(); a<max; a++) {
if ( trimmed.charAt(a) == '.' ) {
dotCount++;
if (dotCount>1) break;
} else if ( !Character.isDigit(trimmed.charAt(a)) ) {
onlyDigits = false;
break;
}
}
if (onlyDigits) {
if (dotCount ==0) {
return VarType.INTEGER;
} else if (dotCount ==1) {
return VarType.FLOAT;
} else {
return VarType.STRING;
}
}
return VarType.STRING;
}
public static void main(String[] args) {
String[] vars = {"", " ", "123", "-5123", "1234.41", "-1234.41", "-1234..41","a12312", "523sdf234sdf.123"};
for (String var: vars) {
System.out.print(var);
System.out.print(": \t");
System.out.println(getVarType(var));
}
}
}
It's quite long for such a simple task, but:
no regexes
at most a single scan of the string
readable (IMO)
fast
However, this solution does not validate the range of the value. String 10000000000 would still be recognized as a VarType.INTEGER even though the value could not fit into an int variable in Java.
Use Double.parseDouble ... (method name changed to isNumber to better reflect the meaning of the method) ...
private boolean isNumber (String amount){
boolean isValid = true;
try {
Double.parseDouble(amount);
}
catch(NumberFormatException e){
isValid = false;
}
return isValid;
}
... and could simplify to ...
private boolean isNumber (String amount){
try {
Double.parseDouble(amount);
}
catch(NumberFormatException e){
return false;
}
return true;
}
As suggested, it would be better to use long and double instead of int and float.
By the way, can't you simply check for a float ? If it is an int, than it can always be a float, potentially rounded with loss of precision.
public static boolean isFloat(String number){
try {
return !new Float(number).isNaN();
} catch (NumberFormatException e){
return false;
}
}
Running demo: https://ideone.com/UpGPsK
Output:
> 1234 IS a valid Integer or Float
> 1234.56 IS a valid Integer or Float
> 1234.56.78 IS NOT a valid Integer or Float
> abc IS NOT a valid Integer or Float
> 2147483647 IS a valid Integer or Float
> 3.4028235E38 IS a valid Integer or Float
> -2147483648 IS a valid Integer or Float
> 1.4E-45 IS a valid Integer or Float
If you're talking about integers or a few decimals, you're probably talking about money or quantities, for which BigDecimal is ideal; and floating-point not really so good (due to rounding errors).
Otherwise, you're talking about a double floating-point value.
new BigDecimal( str) will parse an integer or decimal for you, but it will also accept exponents; eg 1.4E2 means 140.
Perhaps you want to use a regex pattern to validate it first;
if (! str.matches( "[-+]?(\\d+)|(\\d*\\.\\d+)"))
throw new NumberFormatException();
This pattern accepts decimals without any leading digits, such as .14159 -- which should be allowable.

Categories

Resources