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 {
}
});
Related
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;
i'm doing a calculator app and i'm using Decimal Format to format my number.
My problem is i want it to show number like 0,003. But 2 zero after the comma didn't show up until I typing 3. Please help me fix this
Here my code
DecimalFormatSymbols formatSymbolsGermany = DecimalFormatSymbols.getInstance(Locale.GERMANY);
DecimalFormat decimalFormat = new DecimalFormat("#,###,###.########", formatSymbolsGermany);
My code to add "0"
private void zeroOnClick() {
if (tvNumber.getText().toString().length() < 11) {
convertNumber("0");
}
}
private void convertNumber(String number) {
number1 += number;
try {
double a = Double.parseDouble(number1.replace(',', '.'));
tvNumber.setText(decimalFormat.format(a));
delete = true;
} catch (Exception e) {
e.printStackTrace();
}
}
private void addComma(){
if (comma) {
//do nothing
} else {
number1 += ",";
tvNumber.setText(number1);
comma = true;
}
}
The simplest solution would be to just tvNumber.setText(number1); directly without the back-and-forth conversion while editing and display it in the proper format only after the editing is done.
Another possibility would be to artificially append a digit before the conversion if the number contains a decimal point and then remove it afterwards.
String res = number1.replace(',', '.'); // shouldn't this be decimalFormat dependent ?
if( number1.contains(".") ) {
res = decimalFormat.format( Double.parseDouble(res+"5"));
res = res.substring(0,res.length()-1);
} else {
res = decimalFormat.format( Double.parseDouble(res) );
}
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.
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);
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.