I have this Java object which is used to store item:
public class PaymentDetailsItem
{
private String name;
private String amount;
private int quantity;
private String currencyID;
public PaymentDetailsItem(String name, String amount, int quantity, String currencyID){
this.name = name;
this.amount = amount;
this.quantity = quantity;
this.currencyID = currencyID;
}
............
}
I use a List to store several Objects. How can I sum up the total amount from every object store into the List?
You could make use of Java 8 Stream API and implement something like this:
public static void main(String[] args) {
PaymentDetailsItem payment = new PaymentDetailsItem("test", "100.00", 10, "1");
PaymentDetailsItem payment2 = new PaymentDetailsItem("test number 2", "250.00", 10, "2");
List<PaymentDetailsItem> payments = new ArrayList<>();
payments.add(payment);
payments.add(payment2);
List<String> amounts = payments.stream().map(PaymentDetailsItem::getAmount).collect(Collectors.toList());
System.out.println("Here we have the extracted List of amounts: " + amounts);
String totalAmount = amounts.stream()
.reduce((amount1, amount2) -> String.valueOf(Float.valueOf(amount1) + Float.valueOf(amount2))).get();
System.out.println("Total amount obtained by using .reduce() upon the List of amounts: " + totalAmount);
System.out.println("Or you can do everything at once: " + payments.stream().map(PaymentDetailsItem::getAmount)
.reduce((amount1, amount2) -> String.valueOf(Float.valueOf(amount1) + Float.valueOf(amount2))).get());
}
Remember to implement the getter for the amount attribute.
Related
I have a question which requires me to create an enum class with two fields, name (String), and then create a hashmap to generate the output with foreach loops method here.
Expected output:
1 = APPLE, price = 20
2 = STRAWBERRY, price = 70
I try to create two hashmaps to get the output and for loops to get the value but the output is not what I want. May I know how to print the price with the relevant fruits only?
My output:
1 = APPLE
2 = STRAWBERRY
,price=20
,price=70
Enum code here:
enum Fruit {
APPLE("APPLE", 20), STRAWBERRY("STRAWBERRY", 70);
private final int price;
private final String name;
private Fruit(String name, int price) {
this.name = name;
this.price = price;
}
}
main class here
public static void main(String[] args) {
HashMap<Integer, Fruit> foodTable = new HashMap<>();
HashMap<Fruit, Integer> priceTable = new HashMap<>();
foodTable.put(1, Fruit.APPLE);
priceTable.put(Fruit.APPLE, Fruit.APPLE.price);
foodTable.put(2, Fruit.STRAWBERRY);
priceTable.put(Fruit.STRAWBERRY, Fruit.STRAWBERRY.price);
for (Map.Entry<Integer, Fruit> set : foodTable.entrySet()) {
System.out.println(set.getKey() + " = " + set.getValue());
}
for (Map.Entry<Fruit, Integer> set1 : priceTable.entrySet()) {
System.out.println("," +
"price" + "=" + set1.getValue());
}
}
You don't need maps at all, as an enum provides a method to return its values.
Given the enum
enum Fruit {
APPLE("APPLE", 20), STRAWBERRY("STRAWBERRY", 70);
private final int price;
private final String name;
private Fruit(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() { return name; }
public int getPrice() { return price; }
}
You can simply write:
int pos = 0;
for (Fruit fruit : Fruit.values()) {
pos++;
System.out.printf("%d = %s, price = %d%n",
pos, fruit.getName(), fruit.getPrice());
}
Edit: as an enum value also knows its ordinal position you can simplify this to
for (Fruit fruit : Fruit.values()) {
System.out.printf("%d = %s, price = %d%n",
fruit.ordinal()+1, fruit.getName(), fruit.getPrice());
}
I'm new in Java and I have to create an inventory program. The program is:
"A salesman enters his sales in a text file. Every line contains the following (separated by a semicolon; ):
Name of customer (only letters and spaces allowed)
Device sold (smartphone, tablet or laptop)
price (like this ####,##)
date of sale (dd/mm/yy ex. 21/03/21)
Then create a program that does the following:
-Reads from the user the name of the file and opens it. Use the proper exception for the case of the file not existing and ask the user to enter the name of the file again
-Create a class named "Sale" which can store in each of its objects a sale (name, device, price and date, like above). For the device type use ENUM, for the date create a class named "LocalDate"
-Reads the data from the text file and puts them in a dynamic array of 'Sale' objects
-Calculates and prints the total income from the sales for each device type
"
So far I have this:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
public class Files {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("What is the filename?");
String input = in.nextLine();
File file = new File(input);
if(file.exists()){
System.out.println("The file exists. ");
}else {
File file2;
do {
System.out.println("That file does not exist. Please enter the name again. ");
Scanner in2 = new Scanner(System.in);
String input2 = in2.nextLine();
file2 = new File(input2);
if (file2.exists()) {
System.out.println("The file exists. ");
}
} while (!file.exists() && !file2.exists());
}
ArrayList<String> sales = new ArrayList<>();
try(BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Katerina Efstathiou\\Desktop\\JAVA (1) - Files and exceptions\\javaprogrone.txt"))){
String line;
while ((line = br.readLine()) != null)
//Add the line to the array-list:
sales.add(line);
}catch(IOException e){
e.printStackTrace();
}
int listSize = sales.size(); //variable with the size of the list 'sales'
String[] listOfPrices = new String[listSize]; //define an array of the size of the list
}
}
The 'Sale' class:
public class Sale {
private String customerName; //variables are declared as private
//enum class DeviceType - (enum classes represent a group of constants, like final variables)
//Enum is short for "enumerations", which means "specifically listed"
enum DeviceType{
SMARTPHONE,
TABLET,
LAPTOP
}
private double price; //variables are declared as private
public Sale(String firstName, String lastName){ //constructor of Sale class
customerName = firstName+" "+lastName;
price = 0.0;
}
//subclass LocalDate is static ,so I can access it without creating an object of the Sale class
static class LocalDate{
private int Day;
private int Month;
private int Year;
LocalDate(){
Day=0;
Month=0;
Year=0;
}
public void Date(){
System.out.println(Day+"/"+Month+"/"+Year);
}
}
}
And this is the file that I made:
file of sales
So my issue is how to add each object in an array and how do I calculate the income from the sales for each device? (Meaning if I sold 4 smartphones, how much is the total income for these 4 smartphones?).
I'm really desperate...I don't know what else to do and I really need help...
Understanding that you're learning Java, I've tried to be as simple as possible and have updated your code and pointed out the mistakes.
Let's move step by step.
1: Segregating components
DeviceType enum and LocalDate class
public enum DeviceType {
SMARTPHONE,
TABLET,
LAPTOP;
}
public class LocalDate {
private int day;
private int month;
private int year;
public static LocalDate date(String date) {
final String[] path = date.split("/");
final LocalDate result = new LocalDate();
result.day = Integer.parseInt(path[0]);
result.month = Integer.parseInt(path[1]);
result.year = Integer.parseInt(path[2]);
return result;
}
}
Notice how I've made seperate enum for DeviceType (instead of a sub-enum).
In our Sale class we will just use hasA relationship for the above components.
Also, in the date method, I've updated the logic where you can return an instance of LocalDate class based on your input.
2: Using components
public class Sale {
private final String customerName;
private final double price;
private final DeviceType deviceType;
private final LocalDate date;
public Sale(String firstName, String lastName, final String device, final String cost, final String date) { //constructor of Sale class
customerName = firstName + " " + lastName;
price = Double.parseDouble(cost);
deviceType = DeviceType.valueOf(device);
this.date = LocalDate.date(date);
}
public DeviceType getDeviceType() {
return deviceType;
}
public double getPrice() {
return price;
}
public LocalDate getDate() {
return date;
}
public String getCustomerName() {
return customerName;
}
}
In this step, we construct our Sale class using the inputs provided to us.
We will make use of the components we created above.
3: Getting result
List<Sale> sales = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath()))) {
String line;
while ((line = br.readLine()) != null) {
//Add the line to the array-list:
final String[] parts = line.split(";");
final String[] cost = parts[2].split(",");
final String[] names = parts[0].split(" ");
final String firstName = names[0].trim();
final String lastName = names[1].trim();
final String costInteger = cost[0].trim();
final String costDecimal = cost[1].trim();
final String device = parts[1].trim();
final String date = parts[3].trim();
final Sale sale = new Sale(firstName, lastName, device, costInteger + "." + costDecimal, date);
sales.add(sale);
}
} catch (IOException e) {
e.printStackTrace();
}
final DeviceType[] deviceTypes = DeviceType.values();
for (final DeviceType deviceType : deviceTypes) {
double sum = 0;
for (final Sale sale : sales) {
if (sale.getDeviceType().name().equals(deviceType.name())) {
sum += sale.getPrice();
}
}
System.out.println("Income for device " + deviceType.name() + " is " + sum);
}
instead of creating ArrayList sales = new ArrayList<>(); we should create a List of Sale
and also for reading the name of file use the file object you created above in your code.
Once, we all things set-up we will just try to find the sum for all the available DeviceType present in the sales list.
First of all you have to modify constructor, it should takes arguments if we want to create objects and add them to list base on file data, it should look like this:
public Sale(String name, double price){ //constructor of Sale class
customerName = name;
this.price = price;
}
Then the main method should looks like:
public class Files {
public static void main(String[] args) {
ArrayList<String> sales = new ArrayList<>();
try(BufferedReader br = new BufferedReader(new FileReader(/*here put your file path"/Users/aabdelaziz/Desktop/f.txt"))){
String line;
while ((line = br.readLine()) != null)
//Add the line to the array-list:
sales.add(line);
}catch(IOException e){
e.printStackTrace();
}
ArrayList<Sale> listOfSales = new ArrayList<>();
//add sales objects from file to list of sales
for (String s: sales){
String[] saleProperties = s.split(";");
//switch the comma in price number by dot
String[] splitPrice = saleProperties[2].split(",");
double price = Double.parseDouble(splitPrice[0] + "." + splitPrice[1]);
Sale sale = new Sale(saleProperties[0].trim(), price);
listOfSales.add(sale);
}
//calculate total prices
double totalPrices = 0;
for (Sale sale: listOfSales){
//you have to add getPrice Method in Sale class
totalPrices += sale.getPrice();
}
System.out.println(totalPrices);
}
}
//if you interested in date and device type you can add them in constructorenter code here
I must group elements from given list using stream. I want to put them into map (do groupping by variable
'vat' <key=vat, value=list>), then count sum of every objects variable in each key.
I am being stuck in summing stream. I did groupping stream but now, after few hours of coding i still dont know what to do.
Code of function:
public static List<Product> calculatingTaxes(List<Product> products){
Map<Double, List<Product>> productTaxesMap = new HashMap<>();
productTaxesMap = products.stream()
.collect(Collectors.groupingBy(Product::getVat));
System.out.println(productTaxesMap);
return null;
}
sout function is to see what the function is doing, current output
{1.0=[Product{netPrice=100.0, vat=1.0, vatAmount=0.0, grossPrice=100.0},
Product{netPrice=100.0, vat=1.0, vatAmount=0.0, grossPrice=100.0}], 1.23=
[Product{netPrice=100.0, vat=1.23, vatAmount=23.0, grossPrice=123.0},
Product{netPrice=100.0, vat=1.23, vatAmount=23.0, grossPrice=123.0},
Product{netPrice=100.0, vat=1.23, vatAmount=23.0, grossPrice=123.0}], 1.08=
[Product{netPrice=100.0, vat=1.08, vatAmount=8.0, grossPrice=108.0},
Product{netPrice=100.0, vat=1.08, vatAmount=8.0, grossPrice=108.0}]}
code of Product class:
public class Product {
private double netPrice;
private double vat;
private double vatAmount;
private double grossPrice;
public Product(double netPrice, double vat) {
this.netPrice = netPrice;
this.vat = vat;
this.grossPrice = netPrice * vat;
this.vatAmount = grossPrice - netPrice;
}
public double getNetPrice() {
return netPrice;
}
public double getVatAmount() {
return vatAmount;
}
public double getGrossPrice() {
return grossPrice;
}
public double getVat() {
return vat;
}
#Override
public String toString() {
return "Product{" +
"netPrice=" + netPrice +
", vat=" + vat +
", vatAmount=" + vatAmount +
", grossPrice=" + grossPrice +
'}';
}
I want the upper function, to return sum of netPrice, grossPrice and vat amount to every vat key(0-8-23%).
I tried collecting and summing elements using Collectors.grouppingBy(). by filtering etc, but none of them worked.
Assuming your input is:
List<Product> products = Arrays.asList(
new Product(100.0, 1.0),
new Product(100.0, 1.0),
new Product(100.0, 1.23),
new Product(100.0, 1.23),
new Product(100.0, 1.23),
new Product(100.0, 1.08),
new Product(100.0, 1.08)
);
You can do:
Map<Double, Product> vatToReducedProduct = products.stream()
.collect(Collectors.toMap(Product::getVat,
Function.identity(),
(p1, p2) -> new Product(p1.getNetPrice() + p2.getNetPrice(), p1.getVat())));
Output:
{
1.0=Product{netPrice=200.0, vat=1.0, vatAmount=0.0, grossPrice=200.0},
1.23=Product{netPrice=300.0, vat=1.23, vatAmount=69.0, grossPrice=369.0},
1.08=Product{netPrice=200.0, vat=1.08, vatAmount=16.0, grossPrice=216.0}
}
I am creating a program that handles a car dealership. The user has the opportunity to add a car in the store by creating a random 3 digit number.
Now the question is how I can search/delete cars depending on the 3 digit code?
I'm thinking that I need every code that the cars have to save it on an array so I can search and delete afterwards.
I have created a class and certain methods on it, I have also created 5 objects and I'm trying to see if it works on these 5.
Here is the method of the random number:
I use the metritis variable because I can't achieve to place correctly the values on the array so I have to give parameter of 1,2,3,4,5 so I can place them correctly to the array.
package antiprosopeia;
import java.util.Random;
public class Antiprosopeia {
private String company,colour;
private int model,horsePower,speed,price,specialCode,metritis;
private int[] codes = new int[]{0,0,0,0,0};
public Antiprosopeia(String company, String colour, int model, int horsePower, int speed, int price) {
this.company = company;
this.colour = colour;
this.model = model;
this.horsePower = horsePower;
this.speed = speed;
this.price = price;
}
public Antiprosopeia() {
company = ""; colour = ""; model = 0; horsePower = 0; speed = 0; price = 0;
}
public void setRandomNumber(int metritis) {
Random rand = new Random();
int randNum2 = rand.nextInt(900) + 100;
specialCode = randNum2;
codes[metritis] = specialCode;
}
public void printarray() {
for(int i=0; i<codes.length; i++) {
System.out.println(" " + codes[i]);}
}
public void Info() {
System.out.println("Company : " + company + "\nColour : " + colour + "\nModel : " + model + "\nHorse Power : " + horsePower +
"\nSpeed : " + speed + "\nPrice : " + price );
}
public static void main(String[] args) {
Antiprosopeia car1 = new Antiprosopeia("Toyota","red",333,100,2223,8000);
car1.setRandomNumber(0);
Antiprosopeia car2 = new Antiprosopeia("Mercedes","yellow",233,100,2990,9000);
car2.setRandomNumber(1);
Antiprosopeia car3 = new Antiprosopeia("Volkswagen","green",153,100,2780,6000);
car3.setRandomNumber(2);
Antiprosopeia car4 = new Antiprosopeia("Mitsubisi","white",678,140,2600,7000);
car4.setRandomNumber(3);
Antiprosopeia car5 = new Antiprosopeia("Porsche","black",390,1000,2000,30000);
car5.setRandomNumber(4);
}
}
[EDIT] Now when i call the printarray() method it seems that at my array only one value is hold and all the others are zer0s as i defined the array at start of my program
If I were doing this, I would use a HashMap. This way you know that you have a unique 3 digit number, and if you wanted to, you could also store more data. You could do something like:
HashMap<Integer, Car> cars = new HashMap<Integer, Car>();
This example would allow you to add a car object to the map. You don't have to that, but it's an option. If you didn't want to do that, you could do:
HashMap<Integer, String> cars = new HashMap<Integer, String>();
and then do:
cars.put(123, "Description of car");
Using a HashMap would give you more options when storing the data. This would also prevent you from creating an array with 1000 elements, all of which are 0 until you have a value for them. You could easily print out all your numbers by doing:
for(int number : cars.entrySet()){
System.out.println("My car number: " + number);
}
Searching for keys would extremely easy, as you could do:
String description = cars.getKey(123);
If description was null, you would know that there is no key for it.
Your issue is that each Antiprosopeia object has its own codes array. They are not shared.
If you really want each object to have a Random ID, then assign that within the constructor.
public class Antiprosopeia {
private String company,colour;
private int model,horsePower,speed,price,specialCode,metritis;
private int randID;
public Antiprosopeia(String company, String colour, int model, int horsePower, int speed, int price){
this.company = company;
this.colour = colour;
this.model = model;
this.horsePower = horsePower;
this.speed = speed;
this.price = price;
this.randID = new Random().nextInt(900) + 100;
}
public Antiprosopeia(){
this("", "", 0, 0, 0, 0);
}
public int getID() { return this.randID; }
#Override
public String toString() {
return String.format(
"Company : %s\n" +
"Colour : %s\n" +
"Model : %s\n" +
"Horse Power : %d\n" +
"Speed : %d\n" +
"Price : %d\n",
company, colour, model, horsePower, speed, price
);
}
If you want to print all those objects,
public static void main(String[] args) {
List<Antiprosopeia> cars = new ArrayList<Antiprosopeia>();
cars.add(new Antiprosopeia("Toyota","red",333,100,2223,8000));
cars.add(new Antiprosopeia("Mercedes","yellow",233,100,2990,9000));
for (int i = 0; i < cars.size(); i++) {
Antiprosopeia c = cars.get(i);
System.out.println(c.getID());
System.out.println(c);
}
}
package chapter10;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Customer {
private String name;
private String streetAddress;
private String phoneNumber;
private int total;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreetAddress(){
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getTotal(){
return total;
}
public void setTotal(int total){
this.total = total;
}
public static void assign(){
int a = (int) (Math.random() + 10);
int r = (int) (Math.random() + 10);
int f = (int) (Math.random() + 10);
System.out.println(a + r + f + "x" + "x" + "x");
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList <Customer > customerList = new ArrayList <Customer>();
char ans;
do
{
Customer customer = new Customer();
System.out.print("Customer name ");
customer.setName(in.next());
int i = 0;
++i;
System.out.print("Street Address ");
customer.setStreetAddress(in.next());
System.out.print("Phone Number ");
customer.setPhoneNumber(in.next());
customerList.add(customer);
System.out.println("Enter total sales ");
customer.setTotal(in.nextInt());
System.out.println("Would you like to enter in a new customer ( y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
((String) customerList).concat("")
} while(ans == 'y');
for(Customer c: customerList){
System.out.print(c.getName() + "\n" + "Phone number is " +c .getPhoneNumber() +"\n" + "Total sales is "+ c.getTotal() + "\n" + "Address is"+ c.getStreetAddress());
}
for(int i=0; i<customerList.size(); i++){
//System.out.print(customerList.get(i).getName());
}
}
}
I need to assign a number to each value in the arraylist but i am getting an error that says that I have to convert to string (arraylist). How do I add it?
If what I gather from the comments is correct then I believe this is what you want:
Your current assign() is incorrect if you want random values 1-10, it should look like this instead:
public String assign(){
Random rand = new Random();
int a = rand.nextInt(10) + 1;
int r = rand.nextInt(10) + 1;
int f = rand.nextInt(10) + 1;
return a+r+f+"xxx";
}
Customer will look like this:
public class Customer {
private String name;
private String customerNumber;
private String streetAddress;
private String phoneNumber;
private int total;
...
...
...
public String getCustomerNumber() { return this.customerNumber; }
public void setCustomerNumber(String cNumber) { this.customerNumber = cNumber; }
And assigning the numbers should look like this:
for(Customer c : customerList) {
c.setCustomerNumber(assign());
}
Also avoid this line of code, it's a really bad idea:
((String) customerList).concat("")
You should probably rename the customerNumber to customerID.
Hiiii
As i understand you are trying to to add number to each value to arrayList ,And same time you are creating arrayList of customer object, So first understand about arrayList of object,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Customer> al = new ArrayList();
al.add(c1);
al.add(c2);
Here this ArrayList object save only address of customer object so how can you change the address of Customer object ; You can not add number in Customer type ArrayList Object,
There is another way typecast your ArrayList to Object type and then no need to typecast again , you can add any type of object in ArrayList
like this,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Object> al = new ArrayList();
al.add(c1);
al.add(c2);
In your code there's the following line:
((String) customerList).concat("")
Trying to cast a List to a String is doomed to failure - I'm not sure why do you think it should work.
If you want a String representation of the list, you should implement a toString() method in class Customer and then you can do something like:
System.out.println(Arrays.toString(customerList.toArray()));
Instead of using ArrayList, you can use Map. In which you can have the number as key and value as Customer.
http://examples.javacodegeeks.com/java-basics/java-map-example/ Contains the example of using Map
Answer in Storing a new object as the value of a hashmap? contains info about how to use Object as value in HashMap