I was just working on some project and I could not find out what's wrong with the following code :
double getInterest(double amt,double tax){
double diff=0;
double refund=0;
double interest=0;
if(amt>=(tax*0.4)){
diff=amt-(tax*0.4);
System.out.println(" "+diff); //This is not working.Nothing gets printed.
refund=diff; //The value is not being assigned to refund.
} //refund remains to be 0 throughout.
interest=diff*0.01*12;
if(refund>0){
JOptionPane.showMessageDialog(null,"Your refund is: "+refund);
}
return interest;
}
I can't figure out any error in the code. But it is still not working completely.
The errors are given in the code in the form of comments.
Anyone help me to figure out the errors and reslove the issue?
I don't know why the value of diff is not getting printed and why the value of diff is not being assigned to the variable refund.
I'm working in NetBeans and it's not giving any kind of compile-time error.
I've tried to check the values by using the println for both diff and refund But the values are not getting printed.
Well if the statements in the if block are never executed, that implies that there is never a call to this method where the arguments meet the condition amt >= (tax*0.4). So the real question is, what values are you passing to this method?
Your bracketing on the
if(amt>=(tax*0.4){
line is missing a closing ) bracket before the first { bracket. Make sure you check your bracketing and make sure you have all errors turned on in the options menu (if you can).
This code should not compile because of the bracketing error. Check that Netbeans is compiling the right project as this should go crazy at compile time.
You should always use the BigDecimal type when dealing with currency to avoid double precision issues.
Here is the code rewritten in BigDecimal
BigDecimal getInterest(final BigDecimal amount, final BigDecimal tax) {
BigDecimal diff = BigDecimal.ZERO;
BigDecimal refund = BigDecimal.ZERO;
BigDecimal reducedTax = new BigDecimal("0.4").multiply(tax);
System.out.println("Amount is " + amount + ". Tax times 0.4 is " + tax + ".");
if (amount.compareTo(reducedTax) >= 0) {
diff = amount.subtract(reducedTax);
System.out.println(diff);
refund = diff;
}
BigDecimal interest = diff.multiply(new BigDecimal("0.01")).multiply(new BigDecimal("12"));
if (refund.compareTo(BigDecimal.ZERO) > 0) {
JOptionPane.showMessageDialog(null, "Your refund is: " + refund);
}
return interest;
}
Yes, I know it's much uglier. It will also be much slower. But it's new correct.
Onto your issue, presumably the code is not entering the if because amount was not greater than tax * 0.4 - if you are sure that it was then maybe you have already encountered double precision issues.
I have added a println before the if so you can see what the values are before the test happens.
Related
public BigDecimal calculateTotal() {
BigDecimal percent = BigDecimal.valueOf(0.9);
int i = 0;
BigDecimal price = BigDecimal.valueOf(0.0);
while(!myOrders.isEmpty()){
if (!myOrders.get(i).getItem().isBulk() && myMembership == true){
price = price.add(myOrders.get(i).calculateOrderTotal().multiply(percent));
myOrders.remove(i);
}
else{
price = price.add(myOrders.get(i).calculateOrderTotal());
myOrders.remove(i);
}
}
//WHY IS THIS UNREACHABLE?!
return price.setScale(2, RoundingMode.HALF_EVEN);
}
I know that anything after a return statement is unreachable code, but my only return statement is unreachable and I can't figure out why. The while loop is the way it is because I'm grasping at straws, I'm aware that it probably won't do what I want it to do. myOrders is an ArrayList.
EDIT: Since OP said it is an ArrayList, my answer no longer applies.
You never update your index i. This should work:
public BigDecimal calculateTotal() {
BigDecimal percent = BigDecimal.valueOf(0.9);
int i = 0;
BigDecimal price = BigDecimal.valueOf(0.0);
while(!myOrders.isEmpty()) {
if (!myOrders.get(i).getItem().isBulk() && myMembership == true) {
price = price.add(myOrders.get(i).calculateOrderTotal().multiply(percent));
myOrders.remove(i);
} else {
price = price.add(myOrders.get(i).calculateOrderTotal());
myOrders.remove(i);
}
i++; // <-- You were missing this
}
// Not unreachable anymore :)
return price.setScale(2, RoundingMode.HALF_EVEN);
}
Your variable i is never incremented. Depending on what type of Collection myOrders is, removing the 0th element each time may not shift the elements in the collection, and myOrders will never be empty.
There is nothing in the posted code to explain the error.
Since you said your IDE is Eclipse, I suggest to clean the project.
Also, make sure to fix all other errors before looking at this one.
This error doesn't make sense,
I suspect you have other compiler errors in your project,
which somehow cause this as a strange side effect.
After you fix everything else, this one should naturally disappear.
Btw, to see clearer, here's a cleaned up version of the same code, doing exactly the same thing:
BigDecimal percent = BigDecimal.valueOf(0.9);
BigDecimal price = BigDecimal.ZERO;
while (!myOrders.isEmpty()) {
Order first = myOrders.get(0);
BigDecimal subtotal = first.calculateOrderTotal();
if (!first.getItem().isBulk() && myMembership) {
subtotal = subtotal.multiply(percent);
}
price = price.add(subtotal);
myOrders.remove(0);
}
return price.setScale(2, RoundingMode.HALF_EVEN);
Cleaning eclipse solved the problem.
I have been trying to figure out how to make my computer develop a popup window to ask for my hourly pay, then the hours I worked and the total I will have after taxes (15%) Im not really sure what I keep doing wrong...
import javax.swing.JOptionPane;
public class payrollAdam
{
public static void main(String[] args)
{
String hourpay, hours, total,result;
double tax;
double tax = .15;
int total = result * tax;
hourpayString = JOptionPane.showMessageDialog ( "what is your hourly pay?" , "enter hour pay ", JOptionPane.INFORMATION_MESSAGE);
hoursString = JOptionPane.showMessageDialog ( "how much time worked?" , "hours spent:", JOptionPane.INFORMATION_MESSAGE);
resultString = hourpay * hours;
totalString = JOptionPane.showMessageDialog ("");
System.exit(0);
}
}
when I try to compile it states (lines 9 & 10) that the variables "tax" "total" and "income" have already been defined in method "main(String[])" The other errors on line 11: "'*' is a bad operand type for binary operator" and that my methods for showmessagedialog are not suitable (string string integer) also on line 11
Your code has a mess of errors -- you're declaring variables as Strings, then re-declaring the same variables, something not allowed.
Start over, declare your variables once and only once, and with the proper type, and it will likely work. Start by getting rid of:
String hourpay, hours, total,result;
double tax;
Also when your code has a ton of compiler errors, this tells you that your method of creating code is wrong. You should never try to add good code to bad. Always compile early and often and fix all compiler errors before trying to add new code. If you use an IDE such as Eclipse or NetBeans, you'll be flagged immediately if any compiler errors should occur.
Also in the future when asking questions about compiler errors or run time exceptions, always post those error messages with your question. They're important, they often tell you exactly what is wrong. Your lack of this key information is likely why your question was down-voted.
I created a calculator and it works fine. I just need that when an amount is lower than the other so it will give the message "Amount A is less than amount B" instead of the calculation itself.
How can I make it return my message?
Here is my code for the calculation:
public class CalculatorModel
{ // Holds the value of the sum of the numbers
// entered in the view
private double calculationValue;
public void calculateDiscount(double number, double number1,
double number2, double number3, double number4,
double number5)
{
if (number2 == number4 && number3 > number5);
{
//calculationValue = (((number2 / number3) * ((number1)) / number - 1) * 100);
}
}
public double getCalculationValue()
{
return calculationValue;
}
}
You mean something like this? Assuming that you have double A and double B passed from somwhere.
if(A<B){
String message = "Amount "+A+" is less than amount "+B;
return message
}
You need to throw an Exception and catch the exception where you would expect to get the calculation value and display the exception message. For example:
throw new Exception("Amount A is less than amount B");
Obviously format it so that A and B are your actual values.
Observations:
Your question has nothing to do with double to String conversion, which can be done by Double.toString(d) or simply concatenating the double with a String e.g. "The number " + A + " is a double".
throwing an Exception is overkill, IMHO, no point in catching that Exception to do something with it, other than printing it out.
You probably want the user to re-enter numbers A, and B. Thus you should not terminate the execution.
You could use System.err.println("Amount A is less than amount B") in a while loop, so that user re-enters A and B, until the criterion A > B is fulfilled.
If your program has a graphical user interface (GUI), rather than command-line interface (CLI), then you need to pop a JDialog, to notify the user. THere are multiple examples on Java Trail.
double[]percentage=new double[vote.length];
for (int m=0;m<vote.length;m++) {
percentage[m] = (double)(vote[j] / total_votes)*100;
}
I am trying to calculate the percentage for each candidate, although I keep getting an error while I am running the code. I don't know what is the problem.
If vote[j] and total_votes are int, you will get 0.
You need to cast one of them to double before the division :
percentage[m] = ((double)vote[m] / total_votes)*100;
I am writing a program where the application has text fields to enter dollar amounts.
There are methods that need to throw exceptions for items such as dollar amounts less than zero. when doing this I have check for exceptions like this:
if (Double.parseDouble(str) <= 0 || Double.parseDouble(str) > 10000)
throw new InvaildDepositAmount("Deposit Amount " + str);
else
totalBalance += amount;
My question is : Do I need to use the Double.parseDouble(str) every time I want to use this input, such in the InvalidDepositAmount class?
The simple answer is no. You can parse it once and use it as a variable later.
double depositAmount = Double.parseDouble(str);
if (depositAmount <= 0 || depositAmount > 10000)
throw new InvaildDepositAmount("Deposit Amount " + depositAmount);
else
totalBalance += depositAmount;
This is also more efficient because, what if the call to parseDouble were expensive (that is, it took a long time for it to get an answer)? Calling it once would be more efficient and easier to read in the long run.
You can just use a variable.
double x = 0;
try {
double x = Double.parseDouble(str);
} catch(Exception ex) {
throw new InvaildDepositAmount("Deposit Amount " + str)
}
if (x <= 0 || x > 10000) {
throw new InvaildDepositAmount("Deposit Amount " + str)
}
I think it makes to code readable, but I'm not sure if it makes it more efficient because the compiler or JVM could notice that and use that expression just once (and do exactly what i'm doing in the code :))
Looks like you have following cases here:
1. input field that should accept only double numbers
2. some functions which accept limited range of double numbers
Obviously you can cache entered value to avoid redundant invocation of Double.parseDouble. Also you should keep that cached value actual and update it if user changed the value in input field.
In case of exceptions related to limits in your functions you can show some popup, or update status line or whatever is suitable for your application. Or probably you want to limit input field about entered value and validate value after each change.