Search code examples
javastringvariablesdouble

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.


Solution

  • 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.