-1

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}");
        }
    }
gaskiller
  • 9
  • 1

2 Answers2

1

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);
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
Mirco0
  • 306
  • 1
  • 2
  • 8
  • You should never do that. In this case, `System.out.printf(format, params)` is the same as `System.out.println(String.format(format, params))` (add a \n for the newline), except shorter, and idiomatic. – rzwitserloot Sep 21 '22 at 16:24
  • Oh thank you for letting me know, I think this is a good option tho if you want to store in a String, I'll fix my answer – Mirco0 Sep 21 '22 at 16:26
  • Java code should use `%n` rather than `\n` for the line separator. – mernst Aug 04 '23 at 22:53
0

You can use Java's String Templates feature. It is described in JEP 430, and it appears in JDK 21 as a preview feature. Here is an example use:

System.out.println(STR."The total cost is \{total_cost}.");

Java's string templates are more versatile, and much safer, than features in other languagues such as C#'s string interpolation and Python's f-strings. For example, string concatenation or interpolation makes SQL injection attacks possible:

String query = "SELECT * FROM Person p WHERE p.last_name = '" + name + "'";
ResultSet rs = conn.createStatement().executeQuery(query);

but this variant (from JEP 430) prevents SQL injection:

PreparedStatement ps = DB."SELECT * FROM Person p WHERE p.last_name = \{name}";
ResultSet rs = ps.executeQuery();
mernst
  • 7,437
  • 30
  • 45