Overriding toString

Lab Java Beginner 10 points

Create Product(name, price) and override toString() to return NAME @ PRICE with 2 decimals. Read products and print them with println(product).

Input

n, then n lines name price.

Output

n lines.

Example

Input

2
pen 1.5
book 12

Output

pen @ 1.50
book @ 12.00
Sample input available Sample output available
Editor
Java

Hints

Every class inherits toString() from Object; override it.

@Override makes the compiler check you really override something.

Solution explanation

All Java classes extend Object, which provides toString, equals and hashCode.

Show solution
import java.util.Scanner;

class Product {
    final String name;
    final double price;

    Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return String.format("%s @ %.2f", name, price);
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            System.out.println(new Product(sc.next(), sc.nextDouble()));
        }
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD