Generating tracking numbers for orders - java

I have this class which will be used from my main class and will be creating objects of class Sale:
import acm.program.*;
public class Sale {
int size = 0;
public int scode = 0 ; // sell code
public String cname ; // client name
public int cphone ; // client phone
public String sdate ; // selling date
public int cost ; // final cost
public int aItems[] // sold product
public Sale (Item aItems[],String cname, String cphone, String sdate) {
this.aItems = aItems ;
this.cname= cname;
this.sphone= sphone;
this.sdate= sdate;
}
public void setsItems(Items aItems) {
this.aItems= aItems;
}
public void setCname (String name) {
this.name= name;
}
public void setCphone(String cphone) {
this.cphone= cphone;
}
public void setSDate(String sdate) {
this.sdate= sdate;
}
The project says that in my main class I must have a way to review any sale made by entering the unique id number of the sale which will be created in this class. My problem is that I don't know how to set my class so that every time it's called from my main it will generate a new id number, starting from 1 and increasing by 1 every time.
Any ideas?

Use a static member variable to store the ID number of the last sale. A static member is a variable that is part of the class, not the object. This value can get incremented like you want.
Make a new method to access that variable that also increments the variable by one each time you generate a new ID.
In your main, call the Sale.generateNewID() method, then pass that new ID into the constructor of your Sale class.
public class Sale {
public static int idCount = 0;
public static int generateNewID() {
return ++idCount;
}
// this is a new member variable to store the id of the sale
private int id;
// note: added id parameter to constructor
public Sale (int theId, Item aItems[],String cname, String cphone, String sdate) {
this.id = theId;
// other constructor assignments that you had go here.
}
... // rest of your code
}

Related

Chemical inventory program written in Java code won't work

So I have been trying to figure out how to do this for a week now. I am behind in the class due to an accident at work so I have not been participating. I started a chemical inventory program using net-beans IDE and have several errors which I don't understand? The teacher is no help and I've read and viewed video on the subject to no avail. Can some one look at my code and tell me what is wrong please. Below is my code now be gentle as I am VERY new to this. Any help would be appreciated. And this is my first post. Below the code is the requirement for week 4. Thanks in advance!
package chemical.inventory;
import java.util.Scanner;
/**
*
* #author Chris
*/
public class ChemicalInventory {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
Chemical[] chemical;
chemical = new Chemical[4];
chemical[0] = new Chemical("Sodium Hypochlorite","1084","1.29","5000");
chemical[1] = new Chemical("Caustic Soda","2010","1.25","5000");
chemical[2] = new Chemical("Sulfuric Acid","1098","2.10","3000");
chemical[3] = new Chemical("Lime","1010","0.93","2500");
double chemicalValue = 0.0;
System.out.printf("\nInventory value is: $%,2f\n",chemicalValue);
}
private static class Chemical {
private String sodium_Hypochlorite;
public Chemical() {
}
private Chemical(String sodium_Hypochlorite, String string, String string0, String string1) {
this.sodium_Hypochlorite = sodium_Hypochlorite;
}
}
}
class Chemical.Inventory
{
protected String chemicalName;
protected double chemicalPrice;
protected double chemicalStock;
protected double chemicalitemNumber;
public ChemicalInventory(String name, double price, double stock, double itemNumber);
static {
String name;
this.chemicalTitle = title;
double price = 0;
this.chemicalPrice = price;
double stock = 0;
this.chemicalStock = stock;
double itemNumber = 0;
this.chemicalitemNumber = itemNumber;
}
Chemical(String string, String string0, String string1, String string2) {
}
public void setChemicalName(String name)
{
this.chemicalName = name;
}
public String getChemicalName()
{
return chemicalName;
}
public void setChemicalPrice(double price)
{
this.chemicalPrice = price;
}
public double getChemicalPrice()
{
return chemicalPrice;
}
public void setChemicalStock(double stock)
{
this.chemicalStock = stock;
}
public double getChemicalStock()
{
return chemicalStock;
}
public void setChemicalitemNumber(double itemNumber)
{
this.chemicalitemNumber = itemNumber;
}
public double getChemicalitemNumber()
{
return chemicalitemNumber;
}
public double getValue()
{
return this.chemicalStock * this.chemicalPrice;
}
static {
System.out.println();
System.out.println( "Chemical Name:" + chemical.getChemicalTitle());
System.out.println("Chemical Price:" + chemical.getChemicalPrice());
System.out.println("Chemical gallons in stock:" + chemical.getChemicalStock());
}
Modify the Inventory Program to use a GUI. The GUI should display the information one product at a time, including the item number, the name of the product, the number of units in stock, the price of each unit, and the value of the inventory of that product. In addition, the GUI should display the value of the entire inventory, the additional attribute, and the restocking fee.
Modify the Inventory Program by adding a button to the GUI that allows the user to move to the first item, the previous item, the next item, and the last item in the inventory. If the first item is displayed and the user clicks on the Previous button, the last item should display. If the last item is displayed and the user clicks on the Next button, the first item should display.
Add a company logo to the GUI using Java™ graphics classes.
What is wrong with your code, a lot:
You defined Scanner input = new Scanner (System.in); and you never use it
Naming convention, field String sodium_Hypochlorite; i believe should be named name
class Chemical.Inventory dot is invalid character for names in java. If you want define your class to be inner class of other class, place it there, if you want it to be on some path, use packages.
constructor defined in class class Chemical.Inventory first does not have a body
Both constructors defined in class Chemical.Inventory has not matching names with class.
your first static initializer in class Chemical.Inventory is using this and some undefined variables. Logic from that block should be declared in constructor.
your second static initializer in class Chemical.Inventory is using variable chemical which wasnt defined anywhere.

Intro to polymorphism 101 java

I'm making a small RPG. There is an Item class which is the parent of each item in the game. These items could be Potion (which is a class) or Bandage (which is a class).
The Item class looks like this:
public class Item
{
int qty;
String name;
Hero hero1;
public void passHero(Hero hero1)
{
this.hero1 = hero1;
}
public void use()
{
if(qty == 0)
{
System.out.println("You have no more of this item to use.");
}
else
{
qty--;
}
}
public void addInv(int value)
{
qty = qty + value;
}
}
A method for passing in the Hero class.
A method for using an item.
A method for adding to the inventory of the item.
This method activates these item classes:
public void initializeItemInventory()
{
items[0] = new Potion();
items[1] = new Bandage();
}
And this method would theoretically print all the items and their quantities:
public void useInventory()
{
for(int i = 0; i<items.length; i++)
{
System.out.println("Enter: " + i + " for " + items[i].name);
}
int response = input.nextInt();
items[response].use();
}
The Potion class, as an example, has an instance variable like:
String name = "Potion";
So my question. Why isn't the name variable from Potion being called correctly in the useInventory method. It returns null which tells me it's returning the parent class Item name, and not the name of the individual subclass variables.
public class Item
{
int qty;
String name;
...
The Item class already has name, and that's what you access from an Item-typed variable:
items[0].name
So if you have
public class Potion extends Item
{
String name = "Potion";
...
then the Potion class has two name fields:
Potion p = new Potion();
System.out.println(p.name);
System.out.println((Item) p).name);
As you say, you want polymorphism, but it only applies to methods. Therefore you need a getter:
public class Item
{
String name;
public String getName() { return name; }
...
In the Potion subclass you may have
public class Potion extends Item
{
public Potion() { this.name = "Potion"; }
...
and items[0].getName() will now work as expected.
Additional note
I'll add this to show a bit of the power of polymorphism.
If you happened to have the name property always the same for all the instances of the same class, you could easily refactor your getter-based solution by completely eliminating the need to store a name variable:
public class Item
{
public String getName() { return "Generic item"; }
...
public class Potion extends Item
{
#Override public String getName() { return "Potion"; }
...
Instead of declaring a new variable in your subclass like "String name = "Potion";"
Use your constructor to pass the value to your superclass, something like this:
// the Item supuerclass has one constructor
public Item(name) {
this.name = name;
}
// the Potion subclass has one constructor
public Potion() {
super("Potion");
}

Update a single variable of a class in an ArrayList of class in java

I have a class Components:
public class Components {
int numberOfNets;
String nameOfComp;
String nameOfCompPart;
int numOfPin;
public components(int i, String compName, String partName, int pin) {
this.numberOfNets = i;
this.nameOfComp = compName;
this.nameOfCompPart = partName;
this.numOfPin = pin;
}
}
Inside another class I created an arraylist of Components class:
List<Components> compList = new ArrayList<Components>();
Later in the code, I am adding the elements in List in this way:
compList.add(new Components(0,compName,partName,0));
See, here numberOfNets and numOfPin variables in Components class are initiated with 0 values. But these values are getting calculated/incremented in a later part of code and hence I need to update the new values of only these two variables in each list element. Now from ArrayList doc I get the idea of updating a list element using its index by set operation. But I am confused how to set/update a particular variable of a class in an ArrayList of a class. I need to update only these two mentioned variables, not all of the four variables in Components class. Is there any way to do that?
You should add getter/setter to your component class so that outer class can update component's members
public class Components {
private int numberOfNets;
private String nameOfComp;
private String nameOfCompPart;
private int numOfPin;
public components(int i, String compName, String partName, int pin) {
setNumberOfNets(i);
setNameOfComp(compName);
setNameOfCompPart(partName);
setNumOfPin(pin);
}
public void setNumberOfNets(int numberOfNets) {
this.numberOfNets = numberOfNets;
}
// Similarly other getter and setters
}
You can now modify any data by using following code because get() will return reference to original object so modifying this object will update in ArrayList
compList.get(0).setNumberOfNets(newNumberOfNets);
Example code.
public class Main {
public static void main(String[] args) {
List<Components> compList = new ArrayList<Components>();
compList.add(new Components(0, "compName", "partName", 0));
System.out.println(compList.get(0).toString());
compList.get(0).numberOfNets = 3;
compList.get(0).numOfPin = 3;
System.out.println(compList.get(0).toString());
}
}
Your class.
public class Components {
int numberOfNets;
String nameOfComp;
String nameOfCompPart;
int numOfPin;
public Components(int i, String compName, String partName, int pin) {
this.numberOfNets = i;
this.nameOfComp = compName;
this.nameOfCompPart = partName;
this.numOfPin = pin;
}
public String toString() {
return this.numberOfNets + " " + nameOfComp + " " + nameOfCompPart
+ " " + numOfPin;
}
}
The output:
0 compName partName 0
3 compName partName 3

Why every elements of an array changes continuously in Java?

I wanted to create array of an objects. There will be many user objects and I want to keep these user objects in an array. I have a class called Data. I tried and searched a lot but couldn't find the solution. When user enters a new name the names of all objects changes with the given name, and at last when i print all the names it prints the last entered name for several times. Here is my code, it will be much helpful you to understand:
testClass.java
public class testClass {
public static void main(String[] args) {
mainScreen();
}
public static void mainScreen(){
Scanner scan = new Scanner(System.in);
System.out.println("1) Add a new user:");
int choice = scan.nextInt();
switch(choice){
case 1:
System.out.println("Enter name:");
String name = scan.next();
Data.users[Data.count] = new Data(name);
mainScreen();
break;
case 2:
for(int i =0; i<=Data.count; i++){
System.out.println(Data.users[i].name);
}
break;
}
}
}
Data.java
public class Data {
public static Data[] users = new Data[600];
public static String name;
public static int count = 0;
public Data(String name) {
users[count].name = name;
count++;
}
}
I want that every object will have unique name, id, phone number, etc.. Does anybody have a suggestion for me?
Because name is static field of your Data class like count and users.
Remove static modifier from name field.
One solution is to remove the static modifier from name field in Data:
public static Data[] users = new Data[600];
public static int count = 0;
public String name;
public Data(String name) {
this.name = name;
Data.count++;
}
Also modify your for loop, because you'll get a NullPointerException, remove equals from the condition:
for(int i =0; i<Data.count; i++){
First you need to correct your Object structure
you have defined a class Data which contains a static array of Data Class itself
I prefer to have data class as:
class Data {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
create a array of Data class in your testClass
create new Data Object for each input and assign the name to the newly created Object using setName
maintain the count variable in testClass. Increment it each time when you get a new input and use count variable to assign newly created Object to the Data array

Creating a simple stock inventory program - 2nd attempt

I have asked this question before and followed the feedback as best as I could but I am still having one problem with storing the info that the user enters into the array.
Here is the first attempt:
OOP Java: Creating a stock inventory program
So I need to have in total three classes(That's required). The Stock, stock inventory and then the user interface. The purpose of this program is to ask the user to input the company's name, stock rating, price and the number of shares. Of course, I then have to do other things. I think I am okay with the rest, the problem is the stockInterface, the last bit of code that I post below.
public class Stock {
private String companyName;
private String stockRating;
private int price;
private int numberOfShares;
public String getCompanyName() {
return companyName;
}
public int getStockRating() {
return stockRating;
}
public String getPrice() {
return price;
}
public int getNumberOfShares() {
return numberOfShares;
}
public Stock(String companyName, String stockRating, int price, int numberOfShares) {
super();
this.companyName = companyName;
this.stockRating = stockRating;
this.price = price;
this.numberOfShares = numberOfShares;
}
import java.util.*;
public class StockInvetory {
private static final int INVENTORY_SIZE = 12;
private Stock [] stocks;
public StockInvetory() {
stocks = new Stock [INVENTORY_SIZE];
}
public class StockInterface() {
private static StockInventory stockPortfolio;
public static void main (String [] args){
System.out.println ("Stock's name:");
String stockName = console.next();
System.out.println ("Stock's rating");
String stockRating= console.next();
System.out.println ("Stock's price:");
int stockPrice = console.nextInt();
System.out.println ("Numbers of shares: ");
int numberShares= console.nextInt();
stockPortfolio [0]= new Stock(stockName, stockRatings, stockPrice, numberShares);
}
This piece of code doesn't work.
stockPortfolio [0]= new Stock(stockName, stockRatings, stockPrice, numberShares)
Can somebody please show me the proper way to store the info into the array? Thank you very much.
Lots of compile errors...
You have defined stockRating as a String but yet return it as an int:
public int getStockRating() {
return stockRating;
}
The same is true for price.
You have extra parenthesis here:
public class StockInterface() {
^
Also in StockInventory, there are multiple statements in the class block They belong in a method.
console is not instantiated.
stockPortfolio is assigned as an array entry, yet it is a single object, and assigned to the Stock which is not a matching type.
So you've declared the stockPortfolio as an instance of StockInventory. StockInventory is a class not an array, so you can't use stockPortfolio [0] = ... because stockPortfolio is an instance of the class. You have a private member in StockInventory that is an array of Stock class instances. What you need is an accessor method to be able to manipulate it. So change StockInventory as follows:
public class StockInvetory {
/*
All the code you have now ...
*/
public Stock [] getStocks(){
return stocks;
}
public setStocks(Stock [] value){
//maybe some checking here ...
stocks = value;
}
}
Now just a slight change in using the class. You need to use the accessor methods as follows:
public class StockInterface {
/*
What you have just the following line changes ...
*/
stockPortfolio.getStocks()[0] = new Stock(stockName, stockRatings, stockPrice, numberShares);
}
I am assuming you are happy with the way you are initializing the array and that you have decided arrays are better than more dynamic data structures in collections for your specific project. If this is not true have a look at Java Collections they may bring you more joy.

Categories

Resources