2. Write a class called Item. Each item has a number (integer), a name (string),
ID: 3722466 • Letter: 2
Question
2. Write a class called Item. Each item has a number (integer), a name (string), and a price (double). The class should have only one constructor with 2 parameters only. The constructor initializes the item name and number according to the parameters' values, and initializes price to some random double value that is between 0 and 100. The class should also have a void method called show to print the information (number, name, and price) of an Item object; a method called discount that takes a discount amount as a parameter (percentage of discount is 10, 20 or 50%) and then returns the price after applying the discount without changing the price value of the object. Don't include any setters or getters. Add a main function to create different items and display them.Explanation / Answer
package practice;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Item {
int number;
String name;
double price;
public static void main(String[] args) {
Item it = new Item();
}
Item() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number(discount) e, 10 or 20 50");
this.number = sc.nextInt();
Scanner sp = new Scanner(System.in);
System.out.println("Enter the name of item");
this.name = sp.nextLine();
Scanner st = new Scanner(System.in);
System.out.println("Enter the price of item");
this.price = st.nextInt();
display();
}
void display() {
List disp = discount(this.number, this.name, this.price);
System.out.println("Printing the discount% , name of item followed by discounted price");
for (Object di : disp) {
System.out.println(di);
}
}
List discount(int number, String name, double price) {
int n = this.number;
String d = this.name;
double p = this.price;
int s = 100 - n;
int amount = (int) ((s * p) / 100);
List ls = new ArrayList<>();
ls.add(n);
ls.add(d);
ls.add(amount);
return ls;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.