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);