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.
Related
I need help with a specific problem in my class project. The goal of the project is to create a program in which you can register how much shares you own. Information that's required is the company name, how many shares you own and their respective value. I created a GUI class and a class where the information is transferred to. The input comes from a private void. I'm having trouble finding a way to transfer the input from the private void to a an arraylist in a class outside it.
Here is how I initialized the arraylist in the GUI class.
public class GUISharePortfolio_1 extends javax.swing.JFrame {
ArrayList<SharePackage.Share> Package = new ArrayList<SharePackage.Share>();
Next is how I get the company name, number of shares and their value from the GUI. Since it is a private void I have to transfer that information to the SharePackage class.
private void CreatePortfolioButtonActionPerformed(java.awt.event.ActionEvent evt) {
String name;
double number;
double value;
name = CompanyNameField.getText();
number = Double.parseDouble(NumberOfSharesField.getText());
value = Double.parseDouble(ValueOfShareField.getText());
Package.CompanyName(name);
Package.NumberOfShares(number);
Package.ValueOfShare(value);
}
I'm getting an error saying "cannot find symbol" under the CompanyName, NumberOfShares and ValueOfShare.
The public class to which the info should be transferred is this:
package shareportfolio;
import java.util.ArrayList;
public class SharePackage
{
private ArrayList<Share> Package = new ArrayList<Share>();
public class Share
{
private String companyname;
private double numberofshares;
private double valueofshare;
Share(String companyname, double numberofshares, double valueofshare)
{
this.companyname = companyname;
this.numberofshares = numberofshares;
this.valueofshare = valueofshare;
}
public void setCompanyName(String name)
{
companyname = name;
}
public String getCompanyName()
{
return(companyname);
}
public void setNumberOfShares(double number)
{
numberofshares = number;
}
public double getNumberOfShares()
{
return(numberofshares);
}
public void setValueOfShare(double value)
{
valueofshare = value;
}
public double getValueOfShare()
{
return(valueofshare);
}
}
}
I would appreciate any help very much.
You have a field named Package, who's type is ArrayList. ArrayList doesn't have a method called CompanyName. What you're probably trying to do is something like:
Package.add(new SharePackage.Share(companyname, numberofshares, valueofshares));
You have two such fields named 'Package', so not sure which one you're trying to add to. Maybe you're under the impression the fields are somehow the same one. They are not.
BTW: Definitely learn Java coding style before submitting this to anyone. You are naming fields with UpperCamelCase which makes it very difficult for a java programmer to read your code.
user1207705 that was the answer. I modified it to:
String name;
double number;
double value;
name = CompanyNameField.getText();
number = Double.parseDouble(NumberOfSharesField.getText());
value = Double.parseDouble(ValueOfShareField.getText());
Package.add(new SharePackage.Share(name, number, value));
Thank you for your help and I will work on Java coding style.
So I have created an Account class and i wanted to save the user details permenantly for future use. For example, should the user create an account, i would like him/her to be able to use his info including balance in the future.
Please help me!
package mini_project;
import java.util.Random;
import javax.swing.JOptionPane;
public class Account {
private String firstName, surname;
private short transactionNumber;
String input;
private int startingAmount;
public Account(String first, String sur, int amount){
firstName = first;
surname = sur;
startingAmount = amount;
}
public void setFirstName (){
input = JOptionPane.showInputDialog("What Is Your First Name?").toUpperCase();
firstName = input;
}
public String getFirstName (){
return firstName;
}
public void setSurname (){
input = JOptionPane.showInputDialog("What Is Your Surname?").toUpperCase ();
surname = input;
}
public String getSurname (){
return surname;
}
public void setTransactionNumber (){
Random rand = new Random ();
int randomNumber = rand.nextInt(1000)+1;
transactionNumber = (short) randomNumber;
}
public short getTransactionNumber(){
return transactionNumber;
}
public void setShares(){
input = JOptionPane.showInputDialog("How Many Shares Do You Currently Own?");
startingAmount = Integer.parseInt(input);
}
public int getShares(){
return startingAmount;
}
}
You could always make the account class implement Serializable. This will allow you to save and import the object's instance, in this case individual account objects. These instances can be saved into a text file. They can also be encrypted if your program requires more security.
If you want to save the data permanently, You need to use database.
You can make your instance variable static. It will save permanently unless you close the program.
private static String firstName, surname;
private static short transactionNumber;
private static int startingAmount;
Then get the setters and getters. But remove the static word in the functions of setters and getters. You only need static in an instance variable.
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.
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
}
I have following homework about computer store:
There are several class include: Monitor, Case, Mouse, Keyboard.
All the classes have common fields: id, name, price, quantity.
Each class has some unique fields.
All most features are: add, update, delete, find, show list, save, load file
-So, first I will create a class named Product have 4 common fields. Above classes will extends from Product.
-Then, I think I maybe create a ComputerStore class which have a field is items type ArrayList. items stores all objects which are instance of 4 above classes But I'm not sure.
Whether it is reasonable? I need some ideas
Before , I always use ArrayList store for only one class like
List <String> list = new ArrayList<String>();
Now they are multi type. I think it's generic in Java, right??
In case, I want to update for 1 items. I must think about how to change information for them. Ex: mouse for some code, keyboard for another code. Anyway, thank for everybody!
Your approach is 100% reasonable.
You are completely on the right track with "generics". First, check out the official enter link description here.
Next, just think about your data in real world terms, like you are already doing: Monitor, case, mouse, and keyboard are products. Your computer store's inventory is a list of products.
Hint: A list of products.
Put that together with what you learn about generics through that tutorial, and you'll be good to go.
You could use java generic.First create a java collection (ex: List) with supper class type, Product. Now you could add any sub classes (Monitor , Keyboard etc) in your collection (List) that extends of class Product.
public class Product{
}
public class Monitor extends Product{
}
public class Keyboard extends Product{
}
List<Product> products = new ArrayList<Product>();
products.add(new Monitor());
products.add(new Keyboard());
Since you have a superclass (Product), you can have the list's type as Product, i.e.
List<Product> list = new ArrayList<Product>();
list.add(new Mouse());
list.add(new Keyboard());
It will allow you to iterate them and list their name and price without caring for the class, but if you intend to take an item out of the list you'll need to check its actual type (depending on what you do with it).
You can do like below
import java.util.List;
import java.util.ArrayList;
class Test{
public static void main(String... args){
List<MultiObj> multiObjs = new ArrayList();
MultiObj ob = new MultiObj(); multiObjs.add(ob);
ResX xOb = new ResX(); multiObjs.add(xOb);
ResY yOb = new ResY(); multiObjs.add(yOb);
ResZ zOb = new ResZ(); multiObjs.add(zOb);
for (int i = 0; i < multiObjs.size(); i++ ) {
System.out.println(multiObjs.get(i).getV());
}
System.out.println("Waoo its working");
}
}
class MultiObj{
public String greet(){
return "Hello World";
}
public String getV(){
return "Hello World";
}
}
class ResX extends MultiObj{
String x = "ResX";
public String getX(){
return x;
}
public String getV(){
return x;
}
}
class ResY extends MultiObj{
String y = "ResY";
public String getY(){
return y;
}
public String getV(){
return y;
}
}
class ResZ extends MultiObj{
String z = "ResZ";
public String getZ(){
return z;
}
public String getV(){
return z;
}
}
You could do this:
public class Item {
public Item(int id, string name, float price, int amount, int ArrayID) {
if (ArrayID == 1) {
ID1 = id;
name1 = name;
price1 = price;
amount1 = amount;
}
if (ArrayID == 2) {
ID2 = id;
name2 = name;
price2 = price;
amount2 = amount;
}
if (ArrayID == 3) {
ID3 = id;
name3 = name;
price3 = price;
amount3 = amount;
}
if (ArrayID == 4) {
ID4 = id;
name4 = name;
price4 = price;
amount4 = amount;
}
}
//ArrayID #1
public static int ID1;
public static String name1;
public static float price1;
public static int amount1;
//ArrayID #2
public static int ID2;
public static String name2;
public static float price2;
public static int amount2;
//ArrayID #3
public static int ID3;
public static String name3;
public static float price3;
public static int amount3;
//ArrayID #4
public static int ID4;
public static String name4;
public static float price4;
public static int amount4;
public static int[] id = ID1, ID2 ID3, ID4;
//so forth...
}