double + double = String? - java

I have a problem the output is supposed to be double but instead it is string
I am trying to add two double values but it is giving it as a string. I am using eclipse. Currently the program is compiling and running. If anyone have a moment I would appreciate it.Cheers guys. Here is the source code.
import java.util.Scanner;
public class FutureInvestment
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter investment amount: ");
double investmentAmount = input.nextDouble();
System.out.println("Enter monthly interest rate: ");
double monthlyInterestRate = input.nextDouble();
System.out.println("Enter number of years: ");
int numberOfYears = input.nextInt();
double futureInterestValue = investmentAmount * ( Math.pow((1 + monthlyInterestRate), numberOfYears * 12));
System.out.println("Accumulated value is: " + futureInterestValue + investmentAmount);
}
}

You need to format your output. You can use DecimalFormat or you can try the String#format function:
System.out.println(
String.format("Accumulated value is: %.2f",
futureInterestValue + investmentAmount));
So you can get the 2 decimal output. Plus, I recommend to create a variable with your result, so you can turn your code into
double accumulatedValue = futureInterestValue + investmentAmount;
System.out.println(
String.format("Accumulated value is: %.2f", accumulatedValue);

Since you're doing it in a println, it's doing string concatenation. If you want to add the double's together, you need to group them using ().
Try
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));

double accumulatedValue = futureInterestValue + investmentAmount;
System.out.println("Accumulated value is: " + accumulatedValue);
Try this.
You were getting String as result of concatenation, since anything concatenated to a string is converted to string. Therefore, you need to complete the value beforehand as I shown above, or you need parentheses.

I think change it to this would work:
double futureInterestValue = investmentAmount * ( Math.pow((1 + monthlyInterestRate / 100), numberOfYears * 12));
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));

you are missing some brackets, so your statement gets executed from left to right, thus appending the double to the string. You would need something like:
System.out.println("Accumulated value is: " + (futureInterestValue +
investmentAmount));

System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
After the first +, Java has concatenated the first string with the first double, resulting in a string. Then it does another concatenation with the second double. You need to calculate the result first before making a string out of it.

When two operators could be evaluated within a line of code, they do so with a fixed precedence. While this example has been explained by many, you might want to review all of the precedence rules.

You can try:
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
or add a variable like double accumulatedValue=futureInterestValue + investmentAmount;
and then System.out.println("Accumulated value is: " + accumulatedValue);

The problem is your number is getting way too large, and Java switches over to scientific notation when printing the value.
If your monthly interest rate is entered as 4.25 (meaning 4.25%), you have to convert that to the correct decimal representation of 0.0425 before using it in your calculations - you have to divide it by 100. If you don't, the interest rate used will be much larger than you intended; in this case 425%.
In other words, change
double monthlyInterestRate = input.nextDouble();
to
double monthlyInterestRate = input.nextDouble()/100;

Related

Why is it concatenating instead of arithmetic operation?

Scanner sal = new Scanner(System.in);
System.out.print("Enter first_salary: ");
int Salary1 = sal.nextInt();
System.out.print("Enter second_salary : ");
int Salary2 = sal.nextInt();
System.out.print("Combined Salary is " + Salary1 + Salary2);
I am trying to get user input twice, and then print the sum. Instead, the output is concatenating the numbers instead of actually adding them.
Because the + operator associates left to right. Your argument is equivalent to the explicit
(("Combined Salary is " + Salary1) + Salary2)
Since ("Combined Salary is " + Salary1) results in a string, you will concatenate strings. To group differently, adjust the order of operations with parentheses:
System.out.print("Combined Salary is " + (Salary1 + Salary2));
As to why this happens, #MadPhysicist's answer covers that.
As to how to avoid this you can either use parentheses as they said or you can use string formatting, like this:
System.out.println("Combined Salary is %d".formatted(Salary1 + Salary2));
String has had the formatted method since Java 15. If you're stuck with an older version you can use the static format method instead:
System.out.println(String.format("Combined Salary is %d", Salary1 + Salary2));

Unexpected DecimalFormat output - Java

I'm taking my java class, and I'm working on a Tsubo calculator for my assignment. I don't usually ask questions on stack overflow so forgive me if this seems basic. I've done some searching here and tried some of the solutions but none have worked in my case. I'm going to copy just part of my conversion below
```
System.out.println("You have chosen to convert square feet to Tsubo");
System.out.println("Please enter the total sqft you are looking to convert");
sqftInput = keyboard.nextInt();
// Double is converted to string so out put remains an object of the same data type
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + sqftResultAsString + " Tsubo"); `
When I do this, it tells me I can't format a double that the type is not applicable to arguments for DecimalFormat.
When I change it to look like this (offending line is commented out)
' System.out.println("You have chosen to convert square feet to Tsubo");
System.out.println("Please enter the total sqft you are looking to convert");
sqftInput = keyboard.nextInt();
// Double is converted to string so out put remains an object of the same data type
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
//sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + sqftFormatted + " Tsubo");
The program compiles and runs, and when I use 5238 as an input number, then my output looks like this --> 5238.0 is equal to :java.text.DecimalFormat#674dc Tsubo
instead of actually displaying the answer which is 325.07.
I've also tried using some regex formatting using the stringFormat but i wind up getting illegalformatting exception.
Long story short, What I'm trying to achieve is an output that is formatted to 2 decimal places, and then converted to a string that the system outputs as an answer. What am I missing? Is this Decimal Format automatically converting this to a string object?
DecimalFormat is used to produce a formatted String. If you print it directly, it will show its (kind of, it's called idenity hashcode) memory address cause that is what the DecimalFormat.toString() does.
Instead, you should use it to produce your output string and print that directly.
As follows:
sqftResult = sqftInput / TSUBO;
DecimalFormat sqftFormatted = new DecimalFormat("#####.00");
String out = sqftFormatted.format(sqftResult); // or whatever you want to print
//sqftResultAsString = Double.toString(sqftFormatted);
System.out.println(sqftInput + " is equal to :" + out + " Tsubo");
See docs for more details

Rounding to the second decimal place [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
After some awesome help yesterday on this site, I am back with another question. I have my input/output equation the way I want it but need help rounding the decimal off to the hundredths position. The way it is set up now the output of pounds seems to just repeat the answer. I have been inputting 10.2 as the weight in kilograms and the answer I keep receiving in pounds is 22.4422.44. I know it is something with the String.format I am using but after messing with it for quite a while I can't seem to figure it out. I know it is something silly but I have been working on this for a while now and I think my brain may be mush. Below is my program.
//This program converts kilograms to pounds using input/output dialog boxes.
import javax.swing.*;
public class SNHU2_3 {
public static void main (String[] args){
String inputStr;
String outputStr;
double pounds;
double kilograms;
inputStr = JOptionPane.showInputDialog("Enter weight in kilograms");
kilograms = Double.parseDouble(inputStr);
outputStr = ("Kilograms = " + kilograms) + "\n" + ("Pounds = " + (kilograms * 2.2)) + String.format("%.2f", (kilograms * 2.2));
JOptionPane.showMessageDialog(null, outputStr, "Weight Conversion", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
You can just simply use:
kilograms = Double.parseDouble(inputStr);
Math.round(kilograms);
I suggest
outputStr = String.format("Kilograms = %.2f \n Pounds = %.2f", kilograms, (kilograms * 2.2));
I would first of all suggest that you should thoroughly research your question before posting it. There are many related question that are already asked in this forum. Also study a little bit more about String.format.
Next to explain your problem:
outputStr = ("Kilograms = " + kilograms) + "\n" + ("Pounds = " + (kilograms * 2.2)) + String.format("%.2f", (kilograms * 2.2));
What this statement does is it concatenates different strings that you have placed between '+' signs. So we start from the left where your have the String "Kilograms = " so first it is taken then we have kilogram this is basically a double and in your example stores the value 10.2. Now the String becomes "Kilograms = 10.2". After that you have the string "\n". So the string becomes "Kilograms = 10.2\n". Then you have "Pounds = ", so on concatenation the string becomes "Kilograms = 10.2\nPounds = ". After that it hits the expression (kilograms * 2.2) Which in your case is 10.2*2.2 which computes to 22.44 So after concatenation the string becomes "Kilograms = 10.2\nPounds = 22.44". After that it hits String.format("%.2f", (kilograms * 2.2)). The return value of this expression in your case is '"22.44"'. So now the finally concatenated string is "Kilograms = 10.2\nPounds = 22.4422.44" which is finally stored in outputStr. And this is exactly what you get.
I believe that I have been able to explain you what is the problem. SO REMEMBER - you should thoroughly research your question before posting it.

formatting issues with printout statement, doubles java

I'm a newby java guy trying to get my print out statement to format decimal placements.. I know that %.2f works, but for whatever reason when I try to apply the %.2f it bombs.... Not sure what to do.. any advice? thanks in advance!
credits = int
raise = double
System.out.printf("An undergraduate resident student taking " + credits + " currently pays $" + "%,.2f",credtotal);
System.out.println("\n");
System.out.printf("with a increase in tuition of " + (trying to format here) raise + ", per credit will become " + raisecredund + ", and an undergraduate resident taking " + credits + " credits" + " will pay $" +"%,.2f",(credits*(raise*245.73))+ credtotal);;
You appear to be using "%,.2f" with a comma which I don't think is legal. %.2f will print the number to 2 decimal places.
If you want to include a comma ever 3 places like in money you should use a DecimalFormat
DecimalFormat formatter = new DecimalFormat("#,###.00");
final String str1 = String.format("An undergraduate resident student taking %d currently pays $%.2f",credits, credtotal);
EDIT: I didn't notice that you were using printf. You were close:
System.out.printf("An undergraduate resident student taking %d currently pays $%.2f", credits,credtotal);
Using your first example string, you supply the formatting characters inline and then provide an argument for each placeholder. Assuming credtotal is a double and knowing credits is int, the above would yield (with respective values assigned)
An undergraduate resident student taking 1 currently pays $2.00
See creating formatted strings section.

The method println(double) in the type PrintStream is not applicable for the arguments (String, double)

Here is the code:
import java.util.Scanner;
public class MoviePrices {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
double adult = 10.50;
double child = 7.50;
System.out.println("How many adult tickets?");
int fnum = user.nextInt();
double aprice = fnum * adult;
System.out.println("The cost of your movie tickets before is ", aprice);
}
}
I am very new to coding and this is a project of mine for school. I am trying to print the variable aprice within that string but I am getting the error in the heading.
Instead of this:
System.out.println("The cost of your movie tickets before is ", aprice);
Do this:
System.out.println("The cost of your movie tickets before is " + aprice);
This is called "concatenation". Read this Java trail for more info.
Edit: You could also use formatting via PrintStream.printf. For example:
double aprice = 4.0 / 3.0;
System.out.printf("The cost of your movie tickets before is %f\n", aprice);
Prints:
The cost of your movie tickets before is 1.333333
You could even do something like this:
double aprice = 4.0 / 3.0;
System.out.printf("The cost of your movie tickets before is $%.2f\n", aprice);
This will print:
The cost of your movie tickets before is $1.33
The %.2f can be read as "format (the %) as a number (the f) with 2 decimal places (the .2)." The $ in front of the % is just for show, btw, it's not part of the format string other than saying "put a $ here". You can find the formatting specs in the Formatter javadocs.
you are looking for
System.out.println("The cost of your movie tickets before is " + aprice);
+ concatenates Strings. , separates method parameters.
Try this one
System.out.println("The cost of your movie tickets before is " + aprice);
And you can also do that:
System.out.printf("The cost of your movie tickets before is %f\n", aprice);
This will help:
System.out.println("The cost of your movie tickets before is " + aprice);
The reason is that if you put in a coma, you are sending two different parameters. If you use the line above, you add the double onto your string, and then it sends the parameters as a String rather than a String and a double.
It occurs when you use , instead of + i.e:
use this one:
System.out.println ("x value" +x);
instead of
System.out.println ("x value", +x);
I don't know if you have found the answer yet, but I understood that you should write like this:
System.out.println(MessageFormat.format("My name is = {0}, My FirstLetter Name is {1}, Myage is = {2}",Myname,myfirstl,d));

Categories

Resources