Auto update ID in Java - java

This is my school assignment. I need an inventory system which auto-updates product ID when users key-in a new product. I created an array of object named Product with 4 attributes(name,ID,price,quantity). The ID should not need a user input.
This part is in the input() method,which is in a different class from the Object.I didn't pass the ID to the object class like I did to the other three attributes.
x[i] = new Product(name,price,stock);
id = x[i].setID();
part of the object class:
/**
* Constructor
*/
public Product(){
id = 0; name = ""; price = 0.00; quantity = 0;
}
public Product( String n, double p, int q){
setName(n); setPrice(p); setQuantity(q);
}
public void setID(){
this.id = id++;
}
Thank you.

What you have won't work, because id is an instance variable. This means that every product you create will have an ID of 0. And calling setID() on every product you create will set the ID of avery product to 1.
You need a static counter, which would belong to the class, and not to each of its instances:
public class Product {
private static int nextId = 0;
...
public Product(String name, double price, int quantity) {
this.id = Product.nextId;
Product.nextId++;
this.name = name;
this.price = price;
this.quantity = quantity;
}
}
Note that this wouldn't work well in a multi-threaded environment, and that double is a bad choice for prices, but you'll learn that later.
See the Java tutorial for more information about instance and static variables.

Are you looking for a way of generating a unique id for each Product object? If so, the way you've coded it now doesn't work, because each Product has its own id, which is completely independent of all other Product objects. There are a couple of ways you could approach this:-
Look into what static variables mean in Java
Maintain a variable in your code that gets incremented every time you create a Product object. Pass this variable into the constructor of Product.

Related

How To reset appropriate parameters for the modification of existing values in java

I want to change these details of Benze car from user input values.
User will be able to change existing details from user input (ex: Name, Brand..).
How to reset the appropriate parameters to change the existing values?
Automobile Benze[] = new Automobile [5];
Benze[i]=new Automobile(); //Automobile is my class name
do {
System.out.println("01<Mercedize Benze");
String C = T.readLine();
int ch = Integer.valueOf(C).intValue();
switch(ch) {
case 01:
//Details of Benze car
Name = "Benze Class C";
Brand = "Benz";
Start = "On ";
Colour= "Grey";
Fuel = 3.5;
Km = 9;
Oil = 1.2;
water = 2;
for( i=0; i < 1; i++) {
Benze [i] = new Automobile(Name, Brand, Start, Colour, Fuel, Km, Oil, water);
Benze[i].show();
}
} while(exit == true);
Your code seems to be incomplete. Please show us the whole thing, including your automobile class.
Also, please always use meaningful variable names. We can never tell what something like C Is supposed to do.
As for your questions, if I understand correctly, you need to create setters for your properties, and then invoke them.
For example, a setter for a name would be
In the automobile class
public void setName(String newName){ this.name = newName; }
And that's it, you just invoke the method from elsewhere and pass it a name parameter. Do this for each property you want to modify, or create a method that changes all of them. The important part is understanding that you can change the properties by just using this.whatever = something
If you want to mutate ➡️ use setters:
class Automobile {
private String name;
...
public void setName(String name) {
this.name = name;
}
...
}
var auto = Benze[i];
auto.setName("new name");
, but better approach is creation new one
var old = Benze[i];
Benze[i] = new Automobile("new name", old.getBrand, ...);

How to put the increment invoice number to DatabaseReference

I am creating an invoice with increment numbers start from #1 #2 #3 ...., but I have no idea how to start with. Here is the structure I want to have:
Invoice#1
|- info...
Invoice#2
|- info...
Invoice#3
|- info...
DatabaseReference ref
= FirebaseDatabase.getInstance().getReference().child("Invoice#" {increment}); //how to put increment here? if I declare i=1 in myActivity.java, it only runs in one
and this is part of the Invoice model I have
public class Invoice {
String buyer, seller, typeOfPymt;
int total;
String billdate;
int invoice_num;
int discount;
int tax;
int grand_total;
public Invoice(String buyer, String seller, int grand_total, String billdate, int invoice_num, int discount) {
this.buyer = buyer;
this.seller = seller;
this.billdate = billdate;
this.invoice_num = invoice_num;
this.discount = discount;
this.grand_total = grand_total;
}
How can I add increments inside the Model?
There is no way you can pass an "increment" argument to the child() method that can help you read the last invoice number and generate a new incremented one.
In your database, a more appropriate approach would be to use as a key of your invoice a random key that is generated by the push() method and not those incrementing voice numbers. The main reason is scalability, as it is explained by #FrankvanPuffelen in the following post:
How to create auto incremented key in Firebase?
Using the above approach, the number of your invoice will become a property in your invoice object.

Java OOP build an array of objects

Thanks for your help! I abandoned the advanced for loop, and it runs fine now. But the requirement still makes me confused. The requirement is to throw an exception if the test case passes more than 5 objects. But it also says "Do not use java scan, build allocation programmatically". I cannot get the point. If I do not use scan, how can I know how many objects the user passes? How can I decide whether it is more than 5 or equals 5? Or is there a way to populate an array without knowing how many objects I'm going to pass?
Teacher's requirement:
• When populating the array of Book objects, application should throw an exception, if test case passed more object than array capacity. Array capacity is defined as (nBooks = 5 ;). Do not use java scan, build allocation programmatically.
• Use ONLY ARRAY NOT LIST for this assignment.
The Book Class
public class Book {
private int id;
private String name;
private double price;
public Book() {
id = 0;
name = "";
price = 0;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
}
The BookApp Class:
public class BookApp {
public static Book[] populateBooks() {
Scanner input = new Scanner(System.in);
Book[] books = new Book[5];
for (int i = 0; i < books.length; i++) {
books[i] = new Book();
System.out.print("Enter book id: ");
books[i].setId(input.nextInt());
System.out.print("Enter book name: ");
books[i].setName(input.next());
System.out.print("Enter book price: ");
books[i].setPrice(input.nextDouble());
}
return books;
}
}
But it also says "Do not use java scan, build allocation
programmatically". I cannot get the point. If I do not use scan, how
can I know how many objects the user passes? How can I decide whether
it is more than 5 or equals 5? Or is there a way to populate an array
without knowing how many objects I'm going to pass?
"build allocation programmatically" means you don't have to request or parse any user input - just write code to do it directly.
However, the requirements mention a "test case". That means you should have separate logic for managing the array (testing capacity and throwing an exception) and doing this programmatic allocation. It doesn't sound like you're expected to use a testing framework, so simply give the BookApp class the array as instance variable, an addBook() method, and do the testing in its main method.

Using 2D parallel arrays to store data

I am supposed to let up to 16 guests order wine from a menu like this:
The program has to be modular. To place an order, the guest must be shown a list of product types and then variations based on that type. Once the orders are processed I have to show a final report with: total amount made by the winery, most ordered wine product type, and the wine product/variation combo ordered the most times.
I am not sure how to make a method that will search the counter array for the most ordered product type, and then another method that will search the counter array for the most ordered product/variation combo. That is what I need help with.
import javax.swing.JOptionPane;
public class Wine_Taste{
public static void main(String[] args){
String[]wines = {"Riesling", "Chardonnay", "Sauvignon Blanc", "Merlot"};
String[][]wineTypes=
{{"Dry- $4.50", "Off Dry-$4.00", "Sweet- $5.00",},
{"Apple- $6.00", "Lemon-$5.50","Vanilla- $6.00"},
{"Lime-$4.50", "Lemongrass- $6.50","Coconut- $7.00"},
{"Plum- $5.00", "Black Cherry- $7.50","Chocolate- $6.00"}};
}
double[][]prices= {{4.50, 4.00, 5.00},
{6.00, 5.50, 6.00},
{4.50, 6.50, 7.00},
{5.00, 7.50, 6.00}};
int[][]counter ={{0,0,0},
{0,0,0},
{0,0,0},
{0,0,0}};
counter = go(wines,wineTypes,counter,prices);
public static int[][] go(String[] wines, String[][] wineTypes, int[][] counter, double[][] prices){
go2(counter);
double totalCost = 0;
String user;
int x =0;
while (x<=16){
for(int i = 0;i<wines.length;i++){
JOptionPane.showMessageDialog(null,wines[i]);
}
user = JOptionPane.showInputDialog("choose wine 0-3");
int i = Integer.parseInt(user);
for(int j=0;j<wineTypes[i].length;j++){
JOptionPane.showMessageDialog(wineTypes[i][j]);
}
user = JOptionPane.showInputDialog("choose option 0-3");
int j = Integer.parseInt(user);
totalCost += prices[i][j];
counter[i][j]++;
user = JOptionPane.showInputDialog("Order more? y/n");
if (user.equals("y")){
x++;
else{
JOptionPane.showMessageDialog(totalCost);
}
}
}
return counter;
}
}
}
I wouldn't design the program like that. Following some basic object oriented dev principles you can have a wine class with a wine type, price etc, for example:
public class Wine {
String name;
String type;
double price;
public Wine(String name, String type, double price) {
super();
this.name = name;
this.type = type;
this.price = price;
}
//+getters setters
}
Then you can have an order class that keeps the order specific data, like which wine was ordered, the total price etc.
If for any reason you want to keep using the approach of multiple (not easy to manage) arrays then I guess you can create a hashmap where the keys are the wine names and the values the popularity. You can increment by one when a new wine is ordered. You can increment as here:
How to update a value, given a key in a java hashmap?
If for any reason you don't want or can't use this approach then you can create two functions: getPopularProductVarCombo() for the most ordered type per wine, and getMostPopular() for the most popular of all.
To implement getMostPopular you have to find the max value of the array. Here is a good example on how to do this
Print largest number in a 2d array - why do my code print three numbers
To implement getPopularProductVarCombo() then find the max value per line. Any other additional info you might need can be fetched in a similar way.

Can a static variable be updated by calling a method from another class in this circumstance? Java

Say, my Store class has this information...
public class Store {
private Product product1, product2, product3;
private static int productCount = 0;
public Store() {
product1 = new Product();
product2 = new Product();
product3 = new Product();
}
public void setData(String name, int demand, double setup, double unit,
double inventory, double selling) {
if (productCount == 0) {
product1.setName(name);
product1.setDemand(demand);
product1.setSetUpCost(setup);
product1.setUnitCost(unit);
product1.setInvCost(inventory);
product1.setSellPrice(selling);
productCount = 1;
} else if (productCount == 1) {
product2.setName(name);
product2.setDemand(demand);
product2.setSetUpCost(setup);
product2.setUnitCost(unit);
product2.setInvCost(inventory);
product2.setSellPrice(selling);
productCount = 2;
} else if (productCount == 3) {
product3.setName(name);
product3.setDemand(demand);
product3.setSetUpCost(setup);
product3.setUnitCost(unit);
product3.setInvCost(inventory);
product3.setSellPrice(selling);
productCount = 3;
}
}
However, in my Interface class...
private void enterData() {
// Assume the user put in the required inputs here
Store.setData(name, demandRate, setupCost, unitCost, inventoryCost, sellingPrice );
}
When I try to use this code, the productCount variable never changes from zero. Also, when I use another method to show product data, it never shows any information like name & so on (as though nothing was ever input). Something is wrong with how I'm trying to store this information.
I want to set data for only 3 products, but my program won't store any information. One guess of mine is that I can't statically try to address a non-static method to store product information. If so, I'm confused how I could store information for ONLY three products.
On top of that (assuming you can now store product information for 3 products), I want to ask the user if they would like to return to the main menu (a .run() method) or replace product information for one of the three products (which are now full) if they try to add information more than three times. I'm not sure how I could do this?
Thanks.
The code that you provided should not even compile.
You need something like:
public class YourInterfaceClass {
private Store store = new Store();
...
private void enterData() {
// Assume the user put in the required inputs here
store.setData(name, demandRate, setupCost, unitCost, inventoryCost, sellingPrice );
}
}

Categories