0% found this document useful (0 votes)
23 views2 pages

Java Prg1

The document contains a Java program that defines a 'Product' class with attributes for id, name, and price. It prompts the user to input details for multiple products and stores them in an ArrayList. Finally, it displays the list of products entered by the user.

Uploaded by

nayakjahnvi44
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views2 pages

Java Prg1

The document contains a Java program that defines a 'Product' class with attributes for id, name, and price. It prompts the user to input details for multiple products and stores them in an ArrayList. Finally, it displays the list of products entered by the user.

Uploaded by

nayakjahnvi44
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Program:1

import java.util.ArrayList;
import java.util.Scanner;
class Product {
int id;
String name;
double price;
public Product(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}

@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
public class UserDefinedCollection {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Product> products = new ArrayList<>();
// User input for products
int numProducts;
System.out.print("Enter the number of products: ");
numProducts = scanner.nextInt();

for (int i = 0; i < numProducts; i++) {


System.out.println("Enter details for product " + (i + 1));
System.out.print("ID: ");
int id = scanner.nextInt();
System.out.print("Name: ");
String name = scanner.next();
//scanner.nextLine(); // Consume extra newline character
System.out.print("Price: ");
double price = scanner.nextDouble();

products.add(new Product(id, name, price));


}
// Displaying products
System.out.println("\nProducts:");
for (Product product : products) {
System.out.println(product);
}
scanner.close();
}
}

You might also like