I am facing a common compilation error with Cannot find symbols in java. The methods from the class Product cannot be used in the main class. The code is below. I have tried to pass the class in any possible ( to my knowledge means) but with no luck.
The error i get is:
CashRegisterTester.java:108: error: cannot find symbol
double iprice = products[i].getPrice();
^
symbol: variable products
location: class CashRegister
1 error
Here's the code.
import java.util.Scanner;
class CashRegisterTester {
public static void main(String[] args) {
Product[] products = new Product[5];
products[0] = new Product();
products[0].setCode(0);
products[0].setName("psomi");
products[0].setPrice(0.50);
products[1] = new Product();
products[1].setCode(1);
products[1].setName("gala");
products[1].setPrice(1.30);
products[2] = new Product();
products[2].setCode(2);
products[2].setName("mila");
products[2].setPrice(1.80);
products[3] = new Product();
products[3].setCode(3);
products[3].setName("zaxari");
products[3].setPrice(2.40);
products[4] = new Product();
products[4].setCode(4);
products[4].setName("krasi");
products[4].setPrice(13.20);
for (int i = 0; i < 5; i++)
System.out.println("\n Product code: " + products[i].getCode() + " \n Product Name: " + products[i].getName() + "\n Product Price: " +
products[i].getPrice());
System.out.println("Which product would you like to buy?");
Scanner myscanner = new Scanner(System.in);
int iEntered;
iEntered = myscanner.nextInt();
CashRegister register = new CashRegister(products);
register.recordPurchase(iEntered);
System.out.println("Would you like to buy something more? [y/n]");
String answer;
answer = myscanner.next();
while (answer.equals('y')) {
System.out.println("Which product would you like to buy?");
register.recordPurchase(iEntered);
System.out.println("Would you like to buy something more? [y/n]");
answer = myscanner.next();
}
System.out.println("How much money will you give?");
double pay = myscanner.nextDouble();
register.enterPayment(pay);
double change = register.giveChange();
System.out.println(change);
// register.finalReceipt();
}
}
class Product{
//Product fields
public int code;
public String name;
public double price;
//Getters & setters
public int getCode(){
return code;
}
public void setCode(int scode){
code = scode;
}
public String getName(){
return name;
}
public void setName(String sname){
name = sname;
}
public double getPrice(){
return price;
}
public void setPrice(double sprice){
price = sprice;
}
}
public class CashRegister extends Product{
public CashRegister(Product[] products){
purchase = 0;
payment = 0;
}
public void recordPurchase(int i){
double iprice = products[i].getPrice;
double total = purchase + iprice;
purchase = total;
}
public void enterPayment(double amount){
payment = amount;
}
public double giveChange(){
double change = payment - purchase;
purchase = 0;
payment = 0;
return change;
}
private double purchase;
private double payment;
}
The products variable is declared nowhere. This is why you get this exception.
Declare products as a private member of the CashRegister class and initialize it in the CashRegister constructor. See the code below:
public class CashRegister extends Product {
public CashRegister(Product[] products){
purchase = 0;
payment = 0;
this.products=products; // Initialize private member
}
public void recordPurchase(int i){
double iprice = products[i].getPrice();
double total = purchase + iprice;
purchase = total;
}
public void enterPayment(double amount){
payment = amount;
}
public double giveChange(){
double change = payment - purchase;
purchase = 0;
payment = 0;
return change;
}
private double purchase;
private double payment;
private Product[] products; // Declare private member
}
One last note, to prevent resource leaks, NEVER forget to close a Scanner.
So add myscanner.close(); at the end of the main method in the CashRegister class.
Related
My goal is to get an amount for an item and a description of that item. I want to get 10 inputs and their values. I don't know how to store their info without asking for one then the other. I want to be able to ask for the user to input the item then price and then store each of those values.
I was trying to create an array of objects to enter and then was suggested to use arraylists which I kind of understand but don't know how to implement in this case.
import java.util.ArrayList;
public class Invoice {
private ArrayList<Item> listOfItems;
public Invoice() {
listOfItems = new ArrayList<Item>();
}
public void addItem(Item item) {
listOfItems.add(item);
}
public double calculateNetItemCost() {
double netCost = 0;
for(Item currentItem : listOfItems) {
netCost += currentItem.getCost();
}
return netCost;
}
public double calculateTax(double taxRateAsADecimal) {
return calculateNetItemCost() * taxRateAsADecimal;
}
public double calculateGST() {
double GST = calculateNetItemCost() * 0.05;
return GST;
}
public double calculatePST() {
double PST = calculateNetItemCost() * 0.07;
return PST;
}
public double calculateTotalCost() {
double total = calculateGST() + calculatePST() + calculateNetItemCost();
return total;
}
}
public class Item {
private double amount;
private String description;
public Item(String description, double amount) {
this.amount = amount;
this.description = description;
}
public String toString() {
return description + ", $" + String.format("%.2f", amount);
}
public double getCost() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
import java.util.Scanner;
import java.util.ArrayList;
public class CustomerBuild {
public static void main(String[] args) {
ArrayList<String> description = new ArrayList<String>();
ArrayList<Double> amount = new ArrayList<Double>();
Scanner input = new Scanner(System.in);
String userInput;
Item testItem = new Item("Apples", 4.00);
System.out.println(testItem);
Invoice testInvoice = new Invoice();
testInvoice.addItem(testItem);
double subTotal = testInvoice.calculateNetItemCost();
System.out.println(subTotal);
double GST = testInvoice.calculateGST();
System.out.println("GST: " + GST);
double PST = testInvoice.calculatePST();
System.out.println("PST: " + PST);
System.out.println("Total cost: " + testInvoice.calculateTotalCost());
}
}
This code snippet is what are you looking for. Asking the user for input then initializing the object using the values
Scanner input = new Scanner(System.in);
System.out.println("Please enter description(e.g.apple,banana,orange):");
String description =input.nextLine();
System.out.println("Please enter Price(e.g.4.0,5.99):");
Double price = scanner.nextDouble();
Item testItem = new Item(description, price);
For Looping:
for(int i =1;i<10;i++) {
System.out.println("Please enter description(e.g.apple,banana,orange):");
String description =input.nextLine();
System.out.println("Please enter Price(e.g.4.0,5.99):");
Double price = scanner.nextDouble();
testInvoice.addItem(new Item(description, price));
}
So I am doing a project which I want to built a library with two ArrayLists one of the ArrayList'<'Book'>' BookList contains an element named quantity has to greater or equivalent to zero if the quantity of the book is above zero another element called status in the BookList is set to In-stock if it's equal to zero it's set to borrowed. I'm trying to create a method that looks at the BookList and shows the percentage of books that are borrowed. I have done this by going through the list and each time it finds a book with quantity below 1 in other words 0 the counter goes up by one so in the end I just substract the counter from the BookList.size(), divide the result with the BookList.size(), multiply it by 100 and fially print it.
Main Class
public class Main {
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
int uinput;
Library nag;
try{
nag = new Library();
do{
System.out.println("Type 1 to add a book.");
System.out.println("Type 2 to show how many books are borrowed.");
uinput = keyb.nextInt();
if (uinput==1){
nag.addBook();
}
if (uinput==2){
nag.statistics();
}
}while (uinput > 0);
}
catch(Exception e){
System.out.println("Invalid entry.");
}
}//end of main
}//end of class
Book Class
public class Book {
private String Title;
private String Author;
private String ISBN;
private String Publisher;
private String Publication_Date;
private String Price;
private int Quantity;
private String Status;
public Book(){
Title= "";
Author="";
ISBN="";
Publisher="";
Publication_Date="";
Price="";
Quantity=1;
Status="IN-STOCK";
}
//getters
public String gettitle(){return Title;}
public String getauthor(){return Author;}
public String getisbn(){return ISBN;}
public String getpublisher(){return Publisher;}
public String getpublication_date(){return Publication_Date;}
public String getprice(){return Price;}
public int getquantity(){return Quantity;}
public String getstatus(){return Status;}
//setters
public void settitle(String t){Title = t;}
public void setauthor(String a){Author = a;}
public void setisbn(String is){ISBN = is;}
public void setpublisher(String p){Publisher = p;}
public void setpublication_date(String pd){Publication_Date = pd;}
public void setprice(String pr){Price = pr;}
public void setquantity(int q){Quantity = q;}
public void setstatus(String s){Status = s;}
}//end of class
Library Class
public class Library {
private ArrayList<Book> BookList;
public Library(){
BookList = new ArrayList<Book>();
}//end of constructor 1
public Library(ArrayList<Book> l) {
BookList = l;
}//end of constructor 3
public void addBook(){
try{
Scanner keyb = new Scanner(System.in);
Book bo = new Book();
System.out.println("Type the title: ");
String title_input;
title_input = keyb.nextLine();
bo.settitle(title_input);
System.out.println("Type the author: ");
String author_input;
author_input = keyb.nextLine();
bo.setauthor(author_input);
System.out.println("Type the isbn: ");
String isbn_input;
isbn_input = keyb.nextLine();
bo.setisbn(isbn_input);
System.out.println("Type the publisher: ");
String publisher_input;
publisher_input = keyb.nextLine();
bo.setpublisher(publisher_input);
System.out.println("Type the publication date: ");
String publication_date_input;
publication_date_input = keyb.nextLine();
bo.setpublication_date(publication_date_input);
System.out.println("Type the price: ");
String price_input;
price_input = keyb.nextLine();
bo.setprice(price_input);
System.out.println("Type the quantity: ");
int quantity_input = Integer.parseInt(keyb.nextLine());
if (quantity_input >= 0){
bo.setquantity(quantity_input);
if (quantity_input > 0){
bo.setstatus("IN_STOCK");
}
if(quantity_input == 0){
bo.setstatus("BORROWED");
}
BookList.add(bo);
System.out.println("Book added successfully.");
}
}catch(Exception e){
System.out.println("Invalid entry");
}//end of addBook()
public void statistics(){
Book bo = new Book();
int counter = 0;
for(int i=0; i < BookList.size();i++){
bo= BookList.get(i);
int holdquantity = bo.getquantity();
if (holdquantity < 1){
counter++;
}
}
double substraction=BookList.size() - counter;
double division= substraction/BookList.size();
double percentage = division * 100;
System.out.print(percentage + "%");
}//end of statistics()
}//end of class
The problem is that it keeps printing 100.0% when I have a book with quantity of zero and another book with quantity above zero.
So I wanted to know if the problem lies within this code or elsewhere.
Let's say your Book class is as follows:
package com.company;
public class Book {
private int quantity;
public Book(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
And your Main is as follows:
package com.company;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main (String[]args) {
List<Book> bookList = new ArrayList<>(){{
add(new Book(4));
add(new Book(0));
add(new Book(3));
add(new Book(7));
add(new Book(0));
add(new Book(0));
add(new Book(1));
add(new Book(9));
add(new Book(0));
add(new Book(5));
}};
int booksOutOfStock = 0;
for (int i = 0; i < bookList.size(); i++) {
if (bookList.get(i).getQuantity() == 0)
booksOutOfStock++;
}
double percentage = 100d / bookList.size() * booksOutOfStock;
System.out.printf("Out of total %d books, %d are out of stock, which makes %.2f%%", bookList.size(), booksOutOfStock,
percentage);
}
}
So check this code, compare it to yours and see where could the error be, or post complete code here so we can help more.
Output of code above:
Out of total 10 books, 4 are out of stock, which makes 40.00%
OK, so after you posted your code I reviewed it, and apart from doing some things the hard way, your code is "working", all I had to do was add a closing brace in Library class at the end of addBook() method after catch block:
catch(Exception e){
System.out.println("Invalid entry");
} --> } <--- (added)
//end of addBook()
And I fixed your percentage code logic, you code would print out the number of non borrowed books as borrowed percentage, here is that code changed:
double division= (double)counter/BookList.size();
double percentage = division * 100;
System.out.printf("%.2f", percentage);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i am trying to solve the following project where I need to choose out the best customer's based on their purchases. All the necessary details like name,and amount purchased is included in my POJO object(Customer).
I made an ArrayList of Cusomers and trying to access getName()/getAmount method in a for Loop.
import java.util.ArrayList;
import java.util.Scanner;
public class Store {
ArrayList<Customer> Customers = new ArrayList<>();
Customer[] csa = new Customer[1000];
public void addSale(String customerName, double amount) {
String cn = customerName;
double am = amount;
Customer cs = new Customer(cn, am);
Customers.add(cs);
}
public String nameOfBestCustomer() {
String name = null;
//Customer csa=new Customer();
double largest = csa[0].getAmount();
// gives me:java.lang.NullPointerException
for (int i = 1; i < Customers.size(); i++) {
if (largest < csa[i].getAmount()) {
largest = csa[i].getAmount();
name = csa[i].getName();
}
}
// return name+""+largest;
return name;
}
public static void main(String[] args) {
Store s = new Store();
double am;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter Customer name:");
String cn = scanner.next();
if (cn.equals("done")) {
am = 0;
scanner.close();
break;
} else {
System.out.println("Enter Amount:");
am = scanner.nextDouble();
s.addSale(cn, am);
}
}
System.out.println("Best customer " + s.nameOfBestCustomer());
}
}
Is it okay to use Customer[] csa = new Customer[1000]? when I already have an Arraylist for Customers?
Can anybody tell me how to access customer-methods using Array or ArrayList? And also why is largest = csa[0].getAmount() giving me a NullPointerException?
there are many mistakes in your source code like
Customer class constructor was wrong assigned
You were not stored any objects on array so objects are null.
Refer below code i have updated source code, just copy paste it will work...
package demo;
import java.util.ArrayList;
import java.util.Scanner;
public class Store {
ArrayList<Customer> Customers = new ArrayList<Customer>();
Customer[] csa = new Customer[1000];
public void addSale(String customerName, double amount) {
String cn = customerName;
double am = amount;
Customer cs = new Customer(cn, am);
Customers.add(cs);
}
public String nameOfBestCustomer() {
String name = null;
//Customer csa=new Customer();
double largest = Customers.get(0).getAmount();
// gives me:java.lang.NullPointerException
for (int i = 1; i < Customers.size(); i++) {
if (largest < Customers.get(i).getAmount()) {
largest = Customers.get(i).getAmount();
name = Customers.get(i).getName();
}
}
// return name+""+largest;
return name;
}
public static void main(String[] args) {
Store s = new Store();
double am;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter Customer name:");
String cn = scanner.next();
if (cn.equals("done")) {
am = 0;
scanner.close();
break;
} else {
System.out.println("Enter Amount:");
am = scanner.nextDouble();
s.addSale(cn, am);
}
}
System.out.println("Best customer " + s.nameOfBestCustomer());
}
}
class Customer {
private String name;
private double amount;
public Customer(){
}
//#SuppressWarnings("null")
public Customer(String name,double price) {
this.name=name;
this.amount= price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
Output :
Enter Customer name:
ramesh
Enter Amount:
100
Enter Customer name:
pramod
Enter Amount:
200
Enter Customer name:
done
Best customer pramod
Alright so I need help here I created a cash register java file and a retailItem file in my cash register file it cant read a section i put in retailItem because its private. So my question is how do i access that private variable that i wrote in my retailItem class into the cash register file
So here's my code for retailItem
import java.text.DecimalFormat;
public class RetailItem
{
private String description;
private double price;
private double unitsOnHand;
private CostData cost;
public void setDescription(String userDescription)
{
description = userDescription;
}
public void setPrice(double p)
{
price = p;
}
public void setUnitsOnHand(double userUnitsOnHand)
{
unitsOnHand = userUnitsOnHand;
}
public String getDescription()
{
return description;
}
public double getPrice()
{
return price;
}
public double getUnitsOnHand()
{
return unitsOnHand;
}
public RetailItem(RetailItem object2)
{
description = object2.description;
price = object2.price;
unitsOnHand = object2.unitsOnHand;
cost = new CostData(object2.cost.wholeSale,object2.cost.Retail);
}
public RetailItem( String descriptionGet,double pri, double
unitsOnHandGet,double wholeSale,double retail)
{
description = descriptionGet;
price = pri;
unitsOnHand = unitsOnHandGet;
cost = new CostData(wholeSale,retail);
}
public String toString()
{
String str;
DecimalFormat dollar = new DecimalFormat("#,##0.00");
str = "Description: " + description +
"Item Price: " + price +
"\nItem Number: " + unitsOnHand +
"\nWhole Cost: $" + dollar.format(cost.wholeSale) +
"\nRetail Price: $" + dollar.format(cost.Retail);
return str;
}
public class CostData
{
public double wholeSale;
public double Retail;
public CostData(double whole,double re)
{
wholeSale = whole;
Retail = re;
}
public void setRetail(double re)
{
Retail = re;
}
public void setWholeSale(double whole)
{
wholeSale = whole;
}
public double getRetail()
{
return Retail;
}
public double getWholeSale()
{
return wholeSale;
}
}
}
Here is the Cash Register class:
public class CashRegister
{
private RetailItem retail;
private int quantityItem;
private final double SALES_TAX = 0.06;
private int subTotal;
public CashRegister()
{
quantityItem = 0;
subTotal = 0;
}
public CashRegister(RetailItem retailObject,int quantity)
{
retail = new RetailItem(retailObject);
quantityItem = quantity;
}
public RetailItem getRetailItem()
{
return new RetailItem(retail);
}
public double getSubTotal()
{
return quantityItem * retail.cost.getRetail();//Here is where the problem is
}
public double getTax()
{
return SALES_TAX;
}
public double getTotal()
{
return subTotal + SALES_TAX;
}
}
You have a number of options:
If they are in the same package, you can set the access of cost to
default (remove the word private from in front of it.)
Change cost from private to public.
Create a default access (neither private nor public) getCost() method to return cost.
Create a public getCost() method to return cost.
The first option gives read/write access to any class in the same package as RetailItem.
The second option gives read/write access to all classes.
The fourth option gives read-only access to all classes.
protected access could also be an option. Its like package access, but also gives read/write access to subclasses.
See also: In Java, difference between default, public, protected, and private
I started this code and I don't know how to finish it. I need to make the class and test driver for a collection of SalesPeople and their data. I created the salespeople class and constructor. i created the accessors and mutators. I need help combing into this into an arrayList class for my test driver. PLEASE HELP (:
import java.util.*;
public class salesPerson {
//salesPerson fields
private int salespersonID;
private String salespersonName;
private String productType;
private int unitsSold = 0;
private double unitPrice;
//Constructor method
public salesPerson(int salespersonID, String salespersonName, String productType, int unitsSold, double unitPrice)
{
this.salespersonID = salespersonID;
this.salespersonName = salespersonName;
this.productType = productType;
this.unitsSold = unitsSold;
this.unitPrice = unitPrice;
}
//Accessor for salesPerson
public int getSalesPersonID(){
return salespersonID;
}
public String getSalesPersonName(){
return salespersonName;
}
public String getProductType(){
return productType;
}
public int getUnitsSold(){
return unitsSold;
}
public double getUnitPrice(){
return unitPrice;
}
public double getTotalSold(){
return unitsSold * unitPrice;
}
//Mutoators for salesPerson
public void setSalesPersonID(int salespersonID){
this.salespersonID = salespersonID;
}
public void setSalesPersonName(String salespersonName) {
this.salespersonName = salespersonName;
}
public void setProductType(String productType){
this.productType = productType;
}
public void setUnitsSold(int unitsSold){
this.unitsSold += unitsSold;
}
public void setUnitProce(double unitPrice){
this.unitPrice = unitPrice;
}
public static void main(String[] args)
{
ArrayList<salesPerson> salesPeople = new ArrayList<salesPerson>();
Scanner userInput = new Scanner(System.in);
boolean newRecord = true;
int salespersonID;
String salespersonName;
String productType;
int unitsSold = 0;
double unitPrice;
do{
System.out.println("Please enter the Salesperson Inoformation.");
System.out.print("Salesperson ID: ");
salespersonID = userInput.nextInt();
System.out.print("Salesperson Name: ");
salespersonName = userInput.next();
System.out.print("Product Type: ");
productType = userInput.next();
System.out.print("Units Sold: ");
unitsSold = userInput.nextInt();
System.out.print("Unit Price: ");
unitPrice = userInput.nextDouble();
System.out.print("Would you like to enter more data?(y/n)");
String askNew = userInput.next();
newRecord = (askNew.toLowerCase().equals("y")) ? true : false;
}while(newRecord == true);
}
}
You have already created a variable called salesPeople.
After taking all the inputs from user create a new object of SalesPerson and add to the salesPeople at the end in while loop.
Check the Below code for more clarity.
.....
SalesPerson tmp = new SalesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(tmp);
}while (newRecord == true)
....
Put this inside your do-while-loop after you have all the data. You need to create each SalesPerson after you have the data, otherwise the values (id, name...) will just be lost and overwritten in the next loop-iteration
salesPeople.add(new SalesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice));
Because the arraylist salesPeople takes objects of salesPerson you will first want to create an object of salesPerson and then add the salesPerson to the salesPeople arraylist.
salesPerson sp = new salesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(sp);
Put that at the end of your do while right before you ask them if you want to create a new salesPerson.
add below 2 lines(creating sp object and adding it to list) at the end of do that is before the line below
System.out.print("Would you like to enter more data?(y/n)");
SalesPerson sp = new SalesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(sp);