Advanced String Formatting
Part of the Logic & Flow section of Coddy's Java journey — lesson 49 of 59.
String formatting in Java allows you to create formatted strings using format specifiers. The most common ones are %s for strings, %d for integers, and %.2f for decimals.
Format a string with multiple values:
String name = "John";
int age = 25;
String text = String.format("Name: %s, Age: %d", name, age);After executing the above code, text contains:
Name: John, Age: 25
Format decimal numbers with precision:
double price = 19.99;
String formatted = String.format("Price: $%.2f", price);After executing the above code, formatted contains:
Price: $19.99
Challenge
EasyCreate a method named formatData that takes four arguments:
- A String (
name) for a product name - A double (
price) for the product price - An integer (
quantity) for the amount - A String (
format) for output format type
The method should format the data based on these types:
- "basic": return "ITEM: {name}, PRICE: ${price}"
- "detailed": return "PRODUCT: {name}\nPRICE: ${price}\nQUANTITY: {quantity}"
- "total": return "TOTAL FOR {quantity}x {name}: ${total}" (total = price * quantity) All prices should be formatted with exactly 2 decimal places.
Return message:
- If any input is null or invalid format: return "Invalid input"
Cheat sheet
String formatting in Java uses format specifiers with String.format():
%sfor strings%dfor integers%.2ffor decimals with 2 decimal places
Format strings with multiple values:
String name = "John";
int age = 25;
String text = String.format("Name: %s, Age: %d", name, age);
// Result: "Name: John, Age: 25"Format decimal numbers with precision:
double price = 19.99;
String formatted = String.format("Price: $%.2f", price);
// Result: "Price: $19.99"Try it yourself
import java.util.Scanner;
public class Main {
public static String formatData(String name, double price, int quantity, String format) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
double price = Double.parseDouble(scanner.nextLine());
int quantity = Integer.parseInt(scanner.nextLine());
String format = scanner.nextLine();
if (name.equals("null")) name = null;
if (format.equals("null")) format = null;
System.out.println(formatData(name, price, quantity, format));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap5HashSet Part 2
Math - Union of HashSetsMath - Intersection of HashSetMath - Set DifferenceMath - Symmetric DifferenceSubsets and SupersetsIterating Over Sets8Advanced String Operations
StringBuilder BasicsStringBuffer IntroductionRegular Expressions BasicsPattern Matching with RegexString TokenizerAdvanced String Formatting