Change from double to String - java

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.

Related

Syntax error on token "eqn" delete this token

I am fairly new to Java and taking a course but cannot figure out this small syntax error that I keep on getting. I have been researching and staring at the problem for a while now and just cannot figure it out. I am not asking for someone to complete the project just need help with this 1 error. Sorry if I am not posting in the right section. Below is the code....
import java.util.*;
public class SolveEqu {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
double arr[]=new double[3]; //passing array as parameter
System.out.println("Enter the three coefficients of the equation separated by spaces");
for(int i=0;i<3;i++)
arr[i]=sc.nextDouble();
double result[]=solveQuadratic(arr); // unknown
//if result is negative
if(result.length==1) {
System.out.println("The equation has no real roots");
}
//if result is = to zero
else if(result.length==2) {
System.out.println(" The equation has just one real root");
System.out.format("The root is %.2f",result[1]);
}
//if result is positive
else
{
System.out.println("The equation has two real roots");
System.out.format("The root are %.2f and %.2f",result[1],result[2]);
}
}
public static double[] solveQuadratic(double[] eqn) { // method heading from assignment
double discriminant=eqn[1]eqn[1]-(4eqn[0]eqn[2]); // discriminant of the quadratic equation
if(discriminant>0) { // discriminant is positive and has 2 real roots
double r1=(-eqn[1]+Math.sqrt(discriminant))/(2eqn[0]); // equation for square roots
double r2=(-eqn[1]-Math.sqrt(discriminant))/(2eqn[0]); //equation for square roots
double res[]= {2,r1,r2};
return res;
}
else if(discriminant==0) //equal to zero the equation has just one real root
{
double r1=(-eqn[1])/(2eqn[0]);
double res[]= {1,r1};
return res;
}
else // the equation has no real roots
{
double res[]= {0}; //unknown
return res; //unknown
}
}
}
The line that is causing me trouble and throwing errors on is the following ...
double discriminant=eqn[1]eqn[1]-(4eqn[0]eqn[2]);
It says "Invalid float literal number" and "Syntax error on taken "eqn", delete this token"
Could someone help explain what this error means?
The comment by #f1sh was the first of multiple examples of the same problem.
As pointed out, you needed a multiplication operator for eqn[1]*eqn[1].
For 4eqn[0]eqn[2], the same applies. If I remember my quadratics, you are trying to multiply there, so you need 4*eqn[0]*eqn[2]. The line should read:
double discriminant=eqn[1]*eqn[1]-(4*eqn[0]*eqn[2]);
Similarly, in your calculation for r1 and r2, 2eqn[0] should be 2*eqn[0]. That fix is needed in both places you calculate r1.
So, the basic rule is that, in java, you must specify the operator between two symbols. Unlike in math, writing them next to one another does not imply multiplication.

For loop and if statement within a method

I am new to using java and am having some issues in my java class right now and will be needing help with my specific code. I try to look at others questions on here all the time but it's never exactly what I need. Here are my directions:
Create a Java file called CompoundInterestYourLastName. Write a method called computeBalance() that computes the balance of a bank account with a given initial balance and interest rate, after a given number of years. Assume interest is compounded yearly.
Use a loop to control the iterations through the years in your method.
Your method should return a double value.
In your main method, run the following tests to verify your method is working correctly.
System.out.printf("Your total is $%.2f", computeBalance(1000, .045, 3));
// should return $1141.17
I am using eclipse and my only current error is in the comments. I also want some general tips and let me know if my logic is wrong. It probably is. :D
Here is what I have currently although I have been trying different things:
import java.util.Scanner;
import java.lang.Math;
public class CompoundInterestTidwell {
public static void main(String[] args) {
double compInt = computeBalance(1000, 0.045, 3);
System.out.printf("Your new balance is $%.2f", compInt);
}
// Getting arror for line of code below.
// Error: This method must return a result of type double
public static double computeBalance(int P, double r, int t) {
// Formula for compounding interest
// A = P(1+(r/n))^(n(t))
// The examples to check my math had rate already divided by 100 so I left out r/n.
for(int c = 0; c <= t; c++ ) {
// deleted 'n' from equation because it need to equal 1 anyways.
double compInt = Math.pow(P*(1+r), t);
if (c < t) {
c++;
return compInt;
}
}
}
}
Thanks.
Your function computeBalance doesn't guarantee to return a value, because the only return statement is in an if clause, within a loop (making it two conditions deep).
This is a thing the compiler is warning you about. Basically it scans your code and makes sure that a function declared as double will actually return a valid value of type double and so on.
If you add a return statement at the end of the body in the function (or throw an error) it should compile.
I am not exactly sure what your function does in technical terms, but I've rewritten it so it should return the same value, but should now actually compile.
public static double computeBalance(int P, double r, int t) {
// Formula for compounding interest
// A = P(1+(r/n))^(n(t))
// The examples to check my math had rate already divided by 100 so I left out r/n.
double compInt = 0; // Declare compInt outside the loop.
for(int c = 0; c <= t; c++ ) {
// deleted 'n' from equation because it need to equal 1 anyways.
compInt = Math.pow(P*(1+r), t);
if (c < t) {
c++;
break; // Break instead of return, will immediately
// go to the return statement outside the loop.
}
}
return compInt; // Moved the return statement to outside the loop so
// the function always will return a double.
}

Do you have to parse a string to a double every time you want to use it?

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.

Computation error

I've been having trouble with my program. Im supposed to take in 3 variables and plug them into a formula to get an answer. My answer comes out to 0.0 and im not sure what i am doing wrong.
public double compute_cert (int years, double amount, double rate, double certificate)
{
certificate = amount * Math.pow(1 + rate/100, years);
return certificate;
}
The variables rate, amount and years are set up correctly but the answer certificate is always returned as 0.0
public static void main(String[] args)
{
int years = 0;
double amount = 0;
double rate = 0;
double certificate = 0;
char ans;// allows for char
do{
CDProgram C = new CDProgram(years, amount, rate, certificate);
C.get_years();
C.get_amount();
C.get_rate();
C.get_info();
C.compute_cert(years, amount, rate, certificate);
System.out.println ("Would you like to repeat this program? (Y/N)");
ans = console.next().charAt(0);// user enters either Y or y until they wish to exit the program
} while(ans == 'Y'||ans == 'y'); // test of do/while loop
}
Not sure what else to do. Thanks for the help
It looks like you are not assigning the local variables that you are passing into the computation function?
years = C.get_years();
amount = C.get_amount();
rate = C.get_rate();
info = C.get_info();
As it is, the code is just passing 0 for every parameter into your function. Multiplying by 0 will get you 0. If you pass 0, the following line will multiply 0 by some quantity.
certificate = amount * Math.pow(1 + rate/100, years);
It looks like your CDProgram class has fields for years, amount and rate, and your get_ method are prompting the user for the values.
That being the case, it doesn't make sense to pass parameters for them into your calculation method. I would change the method to this.
public double compute_cert () {
certificate = amount * Math.pow(1 + rate/100, years);
return certificate;
}
Then when you call it in main, don't pass any values in. This will just use the values from the fields in the CDProgram class.

Refining an answer to x decimal places in java

I have an assignment and I need to get an input from the user to refine an answer to an x(the input of the user) number of decimal places. I'm going to refine my answer until there aren't any changes in the x decimal place.Can you please help on how I could achieve this answer?
It's not very clear what you are trying to achieve, but I think you want to accept a number and then round it up as the user specifies it.
Java's BigDecimal http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html class has all the functions you may need for this purpose. Please don't use the primary data types (float, double) as they will result in rounding errors sooner or later.
While it is true what #Thihara answers, maybe you need a bit simpler approach. Unless you need the precision of BigDecimal, you can do this:
int x = 4;
double value = 3.141593;
long answer = (long) (value * Math.pow(10, x));
The point is: multiply the value by 10^x and then convert to long (or int). Of course, this only works for small x.
There are a bunch of issues floating around here, that you should be aware of.
The first is that if you use a floating point number to represent your answer, you cannot represent every possible real number so you almost definitely will get rounding errors. Check out http://floating-point-gui.de/ for great information about this.
Secondly, when you print a float or double value, Java does some magic with it so that it looks nice. See Float.toString(float) and Double.toString(double) for more information.
So in reality, if you enter
double answer = 3.14159265;
it is stored as
3.141592650000000208621031561051495373249053955078125
which you can see using
System.out.println(new BigDecimal(answer));
So assuming you get your answer as a double (or float), you should use BigDecimal's setScale method. Also, if you want to limit the decimal places that your user can choose to the number visible when you print the double as a string, pass String.valueOf(answer) to BigDecimal's constructor.
Here is a little program that demonstrates how to do this
public static void main(String[] args) {
double answer = 3.14159265;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String input = null;
do {
System.out.println("Answer: " + answer);
System.out.println("How many decimal places do you want? ");
try {
input = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (input != null) {
try {
int decimalPlaces = Integer.parseInt(input);
if (decimalPlaces < 0) {
System.out.println("Enter a positive value.");
} else {
BigDecimal scaled = new BigDecimal(
String.valueOf(answer));
if (decimalPlaces > scaled.scale()) {
System.out
.println("Answer does not have that many decimal places.");
} else {
scaled = scaled.setScale(decimalPlaces,
RoundingMode.HALF_EVEN);
System.out.println("Rounded answer: " + scaled);
}
}
} catch (Exception e) {
System.out.println("Not a valid number.");
}
}
} while (input != null);
}
Most of the code is error/input checking. The real work is done by setScale. Just keep in mind that there are many boundary conditions when working with floating point numbers, and you should be good!

Categories