Cannot find symbol - class InventoryItem - java

I re-type these code from a book and somehow I got error " Cannot find symbol - class InventoryItem "
import java.util.Scanner;
public class ReturnObject {
public static void main(String[] args) {
InventoryItem item;
item = getData();
System.out.println("Des: " + item.getDescription() + " Unit: " +
item.Units());
}
public static InventoryItem getData() {
String desc;
int units;
Scanner keyboard = new Scanner(System.in);
System.out.print("enter descri: ");
desc = keyboard.nextLine();
System.out.print("number of unit: ");
units = keyboard.nextInt();
return new InventoryItem(desc, units);
}
}
I'm new to java please help
thank you.

I think this should be the InventoryItem you need.
/**
* This class uses three constructors.
*/
public class InventoryItem {
private String description; // Item description
private int units; // Units on-hand
/**
* No-arg constructor
*/
public InventoryItem() {
description = "";
units = 0;
}
/**
* The following constructor accepts a
* String argument that is assigned to the
* description field.
*/
public InventoryItem(String d) {
description = d;
units = 0;
}
/**
* The following constructor accepts a
* String argument that is assigned to the
* description field, and an int argument
* that is assigned to the units field.
*/
public InventoryItem(String d, int u) {
description = d;
units = u;
}
/**
* The setDescription method assigns its
* argument to the description field.
*/
public void setDescription(String d) {
description = d;
}
/**
* The setUnits method assigns its argument
* to the units field.
*/
public void setUnits(int u) {
units = u;
}
/**
* The getDescription method returns the
* value in the description field.
*/
public String getDescription() {
return description;
}
/**
* The getUnits method returns the value in
* the units field.
*/
public int getUnits() {
return units;
}
}
complete example click here and here

The class you are currently in cannot find the class (symbol) InventoryItem. You need to define this class & the getData method.
public class InventoryItem{
private String desc;
private int units;
public InventoryItem(){
Scanner keyboard = new Scanner(System.in);
System.out.print("enter descri: ");
desc = keyboard.nextLine();
System.out.print("number of unit: ");
units = keyboard.nextInt();
}
public static InventoryItem getData() {
return this;
}
}

maybe your InventoryItemclass:
public class InventoryItem {
private String desc;
private int units;
public InventoryItem(String desc, int units) {
this.desc=desc;
this.units=units;
}
public String getDescription() {
return desc;
}
public int Units() {
return units;
}
}

Related

Creating an array with 3 variables

I am trying to create an array of students which will contain 3 different types of students and each of the students will have 3 variables name, and 2 grades.
This is what I have done so far, and it gives me the following error cannot find symbol.
Main class:
public class JavaLab5 {
public static final int DEBUG = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent(Smith,14,15);
s[1] = new MathStudent(Jack,16,19);
s[2] = new MathStudent(Victor,18,21);
s[3] = new MathStudent(Mike,23,28);
s[4] = new ScienceStudent(Dave,32,25);
s[5] = new ScienceStudent(Oscar,28,56);
s[6] = new ScienceStudent(Peter,29,28);
s[7] = new ComputerStudent(Philip,25,38);
s[8] = new ComputerStudent(Shaun,34,39);
s[9] = new ComputerStudent(Scott,45,56);
for (int loop = 0; loop < 10; loop++) {
System.out.println(s[loop].getSubjects());
System.out.print(loop + " >>" + s[loop]);
}
}
}
This is the Student class:
public class Student {
private String name;
//private int age;
//public String gender = "na";
public static int instances = 0;
// Getters
//public int getAge() {
//return this.age;
//}
public String getName() {
return this.name;
}
// Setters
//public void setAge(int age) {
//this.age = age;
//}
public void setName(String name) {
if (JavaLab5.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
/**
* Default constructor. Populates name,age and gender
* with defaults
*/
public Student() {
instances++;
//this.age = 18;
this.name = "Not Set";
//this.gender = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
*/
public Student(String name) {
//this.age = age;
this.name = name;
}
/**
* Gender constructor
* #param gender
*/
//public Student(String gender) {
//this(); // Must be the first line!
//this.gender = gender;
//}
/**
* Destructor
* #throws Throwable
*/
protected void finalize() throws Throwable {
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString () {
return "Name: " + this.name; //+ " Age: " + this.age + " Gender: "
//+ this.gender;
}
public String getSubjects() {
return this.getSubjects();
}
}
and this is the MathStudent class which inherits from the Student class:
public class MathStudent extends Student {
private float algebraGrade;
private float calculusGrade;
/**
* Default constructor
* #param name
* #param algebraGrade
* #param calculusGrade
*/
public MathStudent(String name, float algebraGrade, float calculusGrade) {
super();
this.algebraGrade = algebraGrade;
this.calculusGrade = calculusGrade;
}
public MathStudent() {
super();
algebraGrade = 6;
calculusGrade = 4;
}
// Getters
public void setAlgebraGrade(float algebraGrade){
this.algebraGrade = algebraGrade;
}
public void setCalculusGrade(float calculusGrade){
this.calculusGrade = calculusGrade;
}
// Setters
public float getAlgebraGrade() {
return this.algebraGrade;
}
public float getCalculusGrade() {
return this.calculusGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return(" Math Student >> " + "Algebra Grade: " + algebraGrade
+ " Calculus Grade: " + calculusGrade);
}
}
Check how you instantiate students, i.e.
new MathStudent(Smith,14,15);
The name should be in quotes like "Smith"
new MathStudent("Smith",14,15);
Otherwise Smith will be interpreted as variable and this one is not defined.

Similar Objects Quantity

I have an assignment to make this Restaurant Program. it Consists of an Order Class a product class and the main class. Order has an ArrayList to hold the products. I create an instance of the Order and then I add items through my main method.A product has a name(string) a bar-code(string), and a price(float).
Then I have to output a receipt.But what if a customer orders more of one product? Do I instantiate everything one by one? Is a second Beer Product independent? Should I hold quantities somehow? If I want to add a second beer I have to create a new product Beer2 etc? I don't know beforehand how many products each order will hold and the quantity of each so Is this way of instantiating proper? Thanks
Note: it is still incomplete as I want to deal with this before I move on.
import java.util.Date;
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer);
order1.add(Beef);
System.out.println(order1.getReceipt(30f));
}
}
Order Class(nevermind the name Paraggelia I gave it)
import java.util.ArrayList;
import java.util.Date;
/*Notes to self:
* -Work on Comments
* -Javadocs maybe?
* -try to optimize the rough code.
*/
/*Order class*/
public class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private ArrayList<Product> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new ArrayList<Product>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.add(p);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(int i =0; i<this.listOfItems.size();i++){
receipt.append(listOfItems.get(i).getName());
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
Product Class:
public class Product {
private String Name;
private String barCode;
private float sellingPrice;
/*Constructors: */
Product(){}
Product(String Name,String barCode,float sellingPrice){
this.Name=Name;
this.barCode=barCode;
this.sellingPrice=sellingPrice;
}
/*Getters & Setters*/
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public float getSellingPrice() {
return sellingPrice;
}
public void setSellingPrice(float sellingPrice) {
this.sellingPrice = sellingPrice;
}
}
Instead of ArrayList ( List ) you can use Map ( HashMap for example )
MyRestaurantTester
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer, 1);
order1.add(Beef, 5);
System.out.println(order1.getReceipt(30f));
}
}
Paraggelia
class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private Map<Product, Integer> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new HashMap<Product, Integer>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p, int quantity){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.put(p, quantity);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(Map.Entry<Product,Integer> entry : this.listOfItems.entrySet()) {
Product product = entry.getKey();
Integer quantity = entry.getValue();
receipt.append(product.getName() + " " + quantity);
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
OUTPUT:
Pork Beef 5
Amstel 1
Three basic approaches come to mind:
Instantiate each product individually
Instead of ArrayList, have another structure that can associate items with quantities; or,
Make a class Article, which belongs to a Product: Product beerProduct = new Product("beer", "0129", 1.37); Article beer = new Article(beerProduct), beer2 = new Article(beerProduct).
The first solution gives you a lot of flexibility (e.g. to discount individual articles for, say, being damaged). The second solution is more economical with objects. The third one captures the intuition that all the Heineken bottles are the same. It is really up to what you want to do - both approaches are equally valid, for some purpose.

Searching a list of items with a specific name

I am doing an Object Oriented program which contains a class Catalog and a class Products. Catalog has a method which suppose to search a list of products with a specific name that are read from a file. Everything works but the getProducts is not working.
This is the Catalog class with the getProducts(String name)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*
public class Catalog{
private static int MAX_ITEMS = 10;
private Products[] list;
private int nextItem;
/**
* Default constructor
*/
public Catalog(){
list = new Products[MAX_ITEMS];
nextItem = 0;
}
/**
* Reads items from an input file.
*/
public void loadList(String fileName)
throws FileNotFoundException {
if ( (fileName != null) && (!fileName.equals("")) ) {
Scanner input = new Scanner(new File(fileName));
String newLine = null;
String name = null;
int quantity = 0;
double price = 0.0;
while (input.hasNextLine() && nextItem < MAX_ITEMS) {
if (input.hasNext()) {
name = input.next();
} else {
System.err.println("ERROR Not a String");
System.exit(2);
}
if (input.hasNextInt()) {
quantity = input.nextInt();
} else {
System.err.println("ERROR Not an integer");
System.exit(2);
}
if (input.hasNextDouble()) {
price = input.nextDouble();
} else {
System.err.println("ERROR Not a double");
System.exit(2);
}
list[nextItem] = new Products(name, quantity, price);
newLine = input.nextLine();
nextItem += 1;
}
}
return;
}
/**
* Calculate the total cost of products.
*/
public double getTotalPrice(){
double total = 0.0;
for(int i=0; i < nextItem; i++){
Products products = list[i];
total+=products.getTotalPrice();
}
return total;
}
/**
* Search Catalog items with a product name and returns it to caller
*/
public Products getProducts(String name){
**//search a list for string equality using the name of the product and returns it to the caller**
for(int i=0; i<nextItem; i++){
Products item = list[i];
if(item.equals(name)){
return item; //What is suppose to be returned or how to
//return it to the caller
}
public static void main(String[] args)
throws FileNotFoundException {
Catalog catalog= new Catalog();
catalog.loadList(args[0]);
System.out.println();
System.out.format("Total Price = %9.2f\n", catalog.getTotalPrice());
}
}
This is Products class
public class Products {
private String name;
private int quantity;
private double price;
/**
* Constructor.
*/
public Products(String name, int quantity, double price){
this.name = name;
this.quantity = quantity;
this.price = price;
}
/**
* Gets name of the product.
*/
public String getName(){
return this.name;
}
/**
* Gets the quantity of products.
*/
public int getQuantity(){
return this.quantity;
}
/**
* Gets the cost per product.
*/
public double getPrice(){
return price;
}
/**
* set quantity of the products.
*/
public void setQuantity(int quantity){
this.quantity=quantity;
}
/**
* Calculate the total price.
*/
public double getTotalPrice(){
return quantity * price;
}
/**
* Returns a spaced-separated list of the attributes.
*/
public String toString(){
toStr="";
toStr= toStr + getName();
return toStr;
}
This is the file
Football 2 15.50
Football-Jersey 2 30.95
ChapStick 1 3.87
Book 4 10.00
Book-Journal 1 5.00
You have:
public Products getProducts(String name){
...
for(int i=0; i<nextItem; i++){
...
Products item = list[i];
if(item.equals(name)) {
...
Notice that item is a Products but you are comparing it to the String, name. You would want to compare the product's name, e.g.:
if(item.getName().equals(name)) {
You can also use String.equalsIgnoreCase() if names are case-insensitive, possibly using trim() first if leading/trailing whitespace is an issue, too.
Item is an Object, so you can try to get the name by using dot like this
if(item.getName().equals(name))
or
if(item.getName.equalsIgnoreCase(name))

how to create a method put winecaseback

Hi guys i have created a browser class for my my project , i have created a method called select winecase which selects a winecase, however i am unsure how to
create a method putwinecaseback, which removes the wincase from the shopping basket by calling the method showBasket()
/**
* Write a description of class Browser here.
*
* #author (johnson)
* #version (10/12/13)
*/
import java.util.ArrayList;
import java.util.List;
public class Browser
{
// instance variables - replace the example below with your own
private int iD;
private String email;
private int yearOfBirth;
private boolean memberID;
private WineCase wineCase;
private boolean loggedIn;
private Website website;
private boolean discount;
private List<Boolean> baskets = new ArrayList<Boolean>();
/**
* Constructor for objects of class Browser
*/
public Browser()
{
// initialise instance variables
wineCase = null;
website = null;
iD = 00065;
yearOfBirth = 1992;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = 0;
email = newEmail;
yearOfBirth = newYearOfBirth;
loggedIn = false;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(int newID, String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = newID;
email = newEmail;
yearOfBirth = newYearOfBirth;
memberID = true;
discount = false;
}
/**
* returns the ID
*/
public int getId()
{
return iD;
}
/**
* gets the email of the browser class
*/
public String getEmail()
{
return email;
}
public boolean getDiscount()
{
return discount;
}
/**
* gets the yearOfBirth for the browser class
*/
public int yearOfBirth()
{
return yearOfBirth;
}
public double getWineCost()
{
return wineCase.getWineCost();
}
public double getWineCase()
{
return wineCase.getWineCost();
}
/**
* returns
*/
public void setLoginStatus(boolean status)
{
loggedIn = status;
}
/**
* returns
*/
public void selectWineCase(WineCase winecase)
{
wineCase = winecase;
System.out.println ("Browser "+getId()+" has selcted wine case"+wineCase.getRefNo()+ "of "+winecase.getNoOfBottles()+ wineCase.getDescription()+ " at £"+wineCase.getWineCost());
}
/**
* returns
*/
public void payForWine()
{
website.checkout(this);
}
public void setId()
{
iD = 999;
}
public void setWebSite(Website website)
{
this.website = website;
}
public void setDiscount(boolean discount)
{
this.discount = discount;
}
showBasket()
int counter = 8;
int inc = 1;
while ( counter <= 18 )
{
System.out.print ( " " + counter );
if ( counter >= 14 && counter < 18 )
{
System.out.print ( " hello " );
}
counter = counter + inc;
inc += 1;
}
public ArrayList<WineCase> getBasket(WineCase wineCase)
{
this.wineCase = wineCase;
System.out.println ("Browser "+getId()+" has selcted wine case"+wineCase.getRefNo()+ "of "+wineCase.getNoOfBottles()+ wineCase.getDescription()+ " at £"+wineCase.getWineCost());
}
}
any answers/replies would be greatly appreciated as i am confused.
For this question. Write your putwineCase() method like this:
public void putwineCase()
{
/**
Your logic here
**/
}
This will work. Thankyou.

I am getting the memory address from an arraylist, need info

I am taking a text file and filling an arraylist. To test the file I am printing it out before I move on. I am only able to see the memory address and not the actual info from the file. Is there something simple and probably obvious I'm missing?
public class TriviaQuestion {
private String player;
private String category;
private String question;
private String answer;
private int score = 0;
/**
*
*/
public TriviaQuestion() {
player = "unknown";
category = "unknown";
question = "unknown";
answer = "unknown";
score = 0;
}
public TriviaQuestion(String category, String question, String answer){
}
public TriviaQuestion(String player, String category, String question,
String answer, int score) {
super();
this.player = player;
this.category = category;
this.question = question;
this.answer = answer;
this.score = score;
}
/**
* #return the player
*/
public String getPlayer() {
return player;
}
/**
* #param player the player to set
*/
public void setPlayer(String player) {
this.player = player;
}
/**
* #return the category
*/
public String getCategory() {
return category;
}
/**
* #param category the category to set
*/
public void setCategory(String category) {
this.category = category;
}
/**
* #return the question
*/
public String getQuestion() {
return question;
}
/**
* #param question the question to set
*/
public void setQuestion(String question) {
this.question = question;
}
/**
* #return the answer
*/
public String getAnswer() {
return answer;
}
/**
* #param answer the answer to set
*/
public void setAnswer(String answer) {
this.answer = answer;
}
/**
* #return the score
*/
public int getScore() {
return score;
}
/**
* #param score the score to set
*/
public void setScore(int score) {
this.score = score;
}
}
The tester
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class TriviaQuestionTester {
/**
* #param args
*/
public static void main(String[] args) throws IOException {
File triviaFile = new File("trivia.txt");
Scanner triviaFile1 = new Scanner(triviaFile);
String lastKnownCategory = "";
ArrayList<TriviaQuestion> myList = new ArrayList<TriviaQuestion>();
while (triviaFile1.hasNextLine()){
String currentLine = triviaFile1.nextLine();
if (!currentLine.isEmpty()) {
TriviaQuestion currentQuestion = new TriviaQuestion(currentLine, currentLine, currentLine);
if (currentLine.endsWith("?")) {
currentQuestion.setCategory(lastKnownCategory);
currentQuestion.setQuestion(currentLine);
currentQuestion.setAnswer(triviaFile1.nextLine());
} else {
currentQuestion.setCategory(currentLine);
currentQuestion.setQuestion(triviaFile1.nextLine());
currentQuestion.setAnswer(triviaFile1.nextLine());
lastKnownCategory = currentLine;
}
myList.add(currentQuestion);
}
}
triviaFile1.close();
System.out.println(myList);
}
}
Is there something simple and probably obvious I'm missing?
Yes - you haven't overridden toString in TriviaQuestion, so you're getting the default implementation from Object:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Just add this to TriviaQuestion:
#Override public String toString() {
return "Player: " + player + "; Category: " + category
+ "; Question: " + question + "; Answer: " + answer
+ "; Score: " + score;
}
(Or use String.format within the method to do the same kind of thing.)
You need to override the toString method in your TriviaQuestion class to print the objects in the way you want to. The defualt implementation of toString method prints the memory representation of object.
Note: If you don't know how to write toString method, then make use of some IDE such as eclipse to generate the toString method for you. In eclipse,
go to your class in the editor, right click-> source - > generate
toString.

Categories