Inserting variables into strings

Viewed 33

Im trying to insert the total_cost variable into the string in the last few lines without doing the ("its" + total_cost) method. Im trying to replicate the python {total_variable} method in java basically

    import java.util.Scanner;
    public class Decision2 {
        public static void main(String[] arrgs) {
            Scanner input = new Scanner(System.in);
            int ticket = 0;
            double total_cost = 0;
            System.out.println("How many tickets do you want to buy?");
            ticket = input.nextInt();
            if (ticket >= 5) {
                total_cost = total_cost + (10.95 * ticket);

            } else {
                total_cost = total_cost + (8.95 * ticket);


            }
            System.out.printf("The total cost is {total_cost}");
        }
    }
1 Answers

You can use java String Format such as

String foo = String.format("The total cost is %.2f",total_cost);

or if printing use such as

System.out.printf("The total cost is %.2f\n",total_cost);
Related