Using Accessor methods to access data from another class - java

I am relatively new to java and learning to program, this being my 8th week at uni. I have been fiddling around with my code for the past day and I have been searching for the past hour or two for a similar question that could help answer my problem but have not found one that helps my particular situation, at least not that I could understand.
For an assignment, I have been asked to write a program with 3 classes(an interface, a store and a product class) and I have been going ok until I need to display data on the interface that is held in the product class. At the moment the code will compile fine but when I run the program and try to use the writeOutput() method I get a stack overflow error. Anyway this is what I have so far:
This is the method I am trying to get to work in the interface class:
private void writeOutput()
{
int productChoice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1),(2),(3)");
productChoice = console.nextInt();
System.out.println("The records of product " +productChoice+ " are:");
System.out.println("Name: "+matesStore.getName());
And this is one of the methods from the store class:
public String getName()
{
return getName();
}
Finally I'll include the getter and setter from the product class just in case:
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
Hopefully this is enough information for someone to be able to help me but if it is not, I am happy to upload all three classes in their entirety.
Cheers Cale.
Edit: I have decided to add all three classes to help people who wish to help me (just keep in mind that I am nowhere near finishing and my code is probably riddled with problems) Hopefully it's not too messy for you guys to understand. And sorry for not writing many comments, it's something i need to work on :)
import java.util.*;
public class MatesInterface
{
Store matesStore = new Store();
private void run()
{
showInterface();
chooseOption();
}
private void showInterface()
{
System.out.println("What would you like to do?:");
System.out.println("(1)Input data for the product");
System.out.println("(2)Show data from one product");
System.out.println("(3)Show the replenishment strategy for a product");
System.out.println("(0)Exit the program");
}
private void chooseOption()
{
int option;
boolean flag = false;
Scanner console = new Scanner(System.in);
System.out.print("Please choose an option: ");
option = console.nextInt();
if(option==1)
{
readInput();
}
else if(option==2)
{
writeOutput();
}
else if (option==3)
{
}
else if(option==0)
{
}
else
{
flag = true;
}
while (flag)
{
System.out.println("That is not a valid option.");
System.out.println("Please choose an option: ");
option = console.nextInt();
flag = false;
}
}
private void readInput()
{
Store matesStore = new Store();
String name;
int productChoice, demandRate;
double setupCost, unitCost, inventoryCost, sellingPrice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1), (2) or (3): ");
productChoice = console.nextInt();
System.out.println("Please enter the product's name: ");
name = console.next();
System.out.println("Please enter the product's demand rate: ");
demandRate = console.nextInt();
System.out.println("Please enter the product's setup cost: ");
setupCost = console.nextDouble();
System.out.println("Please enter the product's unit cost: ");
unitCost = console.nextDouble();
System.out.println("Please enter the product's inventory cost: ");
inventoryCost = console.nextDouble();
System.out.println("Please enter the product's selling price: ");
sellingPrice = console.nextDouble();
matesStore.addData(productChoice, name, demandRate, setupCost, unitCost, inventoryCost, sellingPrice);
chooseOption();
}
private void writeOutput()
{
int productChoice;
Scanner console = new Scanner(System.in);
System.out.println("Please choose a product (1),(2),(3)");
productChoice = console.nextInt();
System.out.println("The records of product " +productChoice+ " are:");
System.out.println("Name: "+matesStore.getName());
}
public static void main (String[] args)
{
MatesInterface intFace = new MatesInterface();
intFace.run();
}
}
public class Store
{
// instance variables - replace the example below with your own
private Product product1, product2, product3;
public Store()
{
product1 = new Product();
product2 = new Product();
product3 = new Product();
}
public void addData(int option, String newName, int newDemand, double newSetup, double newUnit, double newInventory, double newPrice)
{
if (option==1) setData(product1, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
else if (option==2) setData(product2, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
else setData(product3, newName, newDemand, newSetup, newUnit, newInventory, newPrice);
}
private void setData(Product product, String name, int demandRate, double setupCost, double unitCost, double inventoryCost, double sellingPrice)
{
product.setName(name);
product.setDemand(demandRate);
product.setSetup(setupCost);
product.setUnit(unitCost);
product.setInventory(inventoryCost);
product.setPrice(sellingPrice);
}
public String getName()
{
return getName();
}
}
import static java.lang.Math.*;
public class Product
{
private String name;
private int demandRate;
//private final int REPLENISHMENTRATE=0;
private double setupCost;
private double unitCost;
private double inventoryCost;
private double sellingPrice;
//Constructors for the class Product
public Product()
{
name = "No name yet.";
demandRate = 0;
unitCost = 0;
setupCost = 0;
inventoryCost = 0;
sellingPrice = 0;
}
public Product(String newName, int newDemand, double newSetup, double newUnit, double newInventory, double newPrice)
{
name = newName;
demandRate = newDemand;
unitCost = newUnit;
setupCost = newSetup;
inventoryCost = newInventory;
sellingPrice = newPrice;
}
// Accessor and mutator methods to access and modify data on a Product object
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void setDemand(int newDemand)
{
demandRate = newDemand;
}
public int getDemand()
{
return demandRate;
}
public void setUnit(double newUnit)
{
unitCost = newUnit;
}
public double getUnit()
{
return unitCost;
}
public void setSetup(double newSetup)
{
setupCost = newSetup;
}
public double getSetup()
{
return setupCost;
}
public void setInventory(double newInventory)
{
inventoryCost = newInventory;
}
public double getInventory()
{
return inventoryCost;
}
public void setPrice(double newPrice)
{
sellingPrice = newPrice;
}
public double getPrice()
{
return sellingPrice;
}
}

The method from the store class is recursivelly calling itself with no terminating clause, this is leading to StackOverflowError :
public String getName()
{
return getName(); // calls itself
}
Instead return the value of name variable if it exists in Store class, or whatever variable you want to be returned as a name:
public String getName()
{
// determine the product name you want
return myProduct.getName();
}

Related

To make the object variable private in another class

I have written the code this expected output:
Sample input :
Enter the passenger name:
Priya
Enter the gender(M or F / m or f):
F
Enter the age:
61
Enter the ticket no:
140
Enter the ticket price:
500.0
Sample Output 1 :
Ticket no:143
Passenger Name:Priya
Price of a ticket : 500.0
Total Amount : 375.0
I have to change the total amount value based on the age and gender for which I have written function.
My code:
Person.java
public class Person {
private String name;
private char gender;
private int age;
public void setName(String name ){
this.name = name;
}
public void setGender(char gender){
this.gender = gender ;
}
public void setAge(int age ){
this.age = age;
}
public String getName(){
return this.name;
}
public char getGender(){
return this.gender;
}
public int getAge(){
return this.age;
}
}
BusTicket.java
public class BusTicket {
private int ticketNo;
private float ticketPrice;
private float totalAmount;
Person person = new Person();
int age = person.getAge();
char g = person.getGender();
public void setTicketNo(int ticketNo){
this.ticketNo = ticketNo;
}
public void setTicketPrice(float ticketPrice){
this.ticketPrice = ticketPrice;
}
public void setTotalAmount(float totalAmount){
this.totalAmount = totalAmount;
}
public void calculateTotal()
{
if(age<16)
{
totalAmount = ticketPrice/2;
setTotalAmount(totalAmount);
}
else if(age>=60)
{
totalAmount = 3*(ticketPrice/4);
setTotalAmount(totalAmount);
}
else if(g == 'f'|| g== 'F')
{
totalAmount = 9*(ticketPrice/10);
setTotalAmount(totalAmount);
}
else{
setTotalAmount(ticketPrice);
}
}
public int getTicketNo(){
return this.ticketNo;
}
public float getTicketPrice(){
return this.ticketPrice;
}
public float getTotalAmount(){
return this.totalAmount;
}
}
TestMain.java
import java.util.Scanner;
public class TestMain {
public static BusTicket getTicketDetails()
{
Scanner sc = new Scanner(System.in);
BusTicket bt = new BusTicket();
System.out.println("Enter the ticket no:");
bt.setTicketNo(sc.nextInt());
System.out.println("Enter the ticket price:");
bt.setTicketPrice(sc.nextFloat());
return bt;
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
Person p = new Person();
BusTicket bt;
System.out.println("Enter the passenger name:");
p.setName(sc.nextLine());
System.out.println("Enter the gender(M or F/ m or f):");
p.setGender(sc.next().charAt(0));
System.out.println("Enter the age:");
p.setAge(sc.nextInt());
bt = getTicketDetails();
System.out.println("Ticket no:"+bt.getTicketNo());
System.out.println("Passenger Name:"+p.getName());
System.out.println("Price of a ticket : "+bt.getTicketPrice());
System.out.println("Total Amount : "+bt.getTotalAmount());
}
}
But my TotalAmount value is always coming 0.0, it is not getting updated.
And some test cases are failed please help to resolve them:
Fail 1 -
Incorrect access specifier/modifier for person -Should be a [private]
Fail 2 -
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method setPerson is correct
Fail 3-
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method getPerson is correct
Please Help
Thanks
You need to call calculateTotal to update totalAmount. Otherwise, it will be always 0.0.
...
System.out.println("Price of a ticket : "+bt.getTicketPrice());
bt.calculateTotal(); // Add this line
System.out.println("Total Amount : "+bt.getTotalAmount());
In your BusTicket class a new Person object is assigned to Person attribute and then you are trying to get age and gender details from that newly created Person object, but at this moment Person's age and gender are not populated yet.
Person person = new Person();
int age = person.getAge();
That's why you are getting 0. What should ideally happen is, you should pass the person object created using the input details to the BusTicket class and populate the BusTicket's person attribute with that person.For now I ll tell just that. :)
Give a try :)
In your BusTicket class, create a getter and setter for the Person object, and set the value from the main method.

Having trouble with constructors and user-input

I'm working on a little project, but I'm having trouble. It has to do with creating classes, constructors, etc. For the class, all data fields have to be private. I must also have two constructors, one default and one parameterized. Here's the class:
public class PetInfo {
private String petName = "na";
private boolean petType = true;
private String petBreed = "na";
private double petAge = 0;
private double petWeight = 0;
private String ownerName = "na";
public PetInfo(){}
public PetInfo(String name, boolean type, String breed, double age, double weight, String owner){
this.petName = name;
this.petType = type;
this.petBreed = breed;
this.petAge = age;
this.petWeight = weight;
this.ownerName = owner;
}
public String getName (){
return petName;
}
public void setName(String name){
petName = name;
}
public boolean getType(){
return petType;
}
public void setType(boolean type){
petType = type;
}
public String getBreed(){
return petBreed;
}
public void setBreed(String breed){
petBreed = breed;
}
public double getAge(){
return petAge;
}
public void setAge(double age){
petAge = age;
}
public double getWeight(){
return petWeight;
}
public void setWeight(double weight){
petWeight = weight;
}
public String getOwner(){
return ownerName;
}
public void setOwner(String owner){
ownerName = owner;
}
}
Here is what I have in my main function:
import java.util.Scanner;
public class Pp1_C00019540 {
public static void main(String[] args) {
PetInfo[] info = new PetInfo[5];
collectInfo(info);
}
public static void collectInfo(PetInfo[] info){
Scanner input = new Scanner(System.in);
for(int i = 0; i < info.length;i++){
System.out.print("Enter pet name: ");
}
}
}
So it prints "Enter pet name: ", but it won't let me input a name. I tried to do:
info[i] = new PetInfo(input.nextLine());
But it tells me "constructor PetInfo.PetInfo(String, boolean, String, double,double, String) is not applicable. Actual and formal arguments differ in length." Is there something wrong with my class that I'm not catching? I tested it and it seemed to work correctly.
And I'm not looking for a definite answer, I could more than likely figure it out myself. I'm just not sure what's going on, especially when it seemed to me like this would work when I passed the constructor the correct parameters.
Basically, your code is trying to call the PetInfo constructor that takes a single string as input. But based on the code you have, no such constructor exists. You just have the large multi-parameter constructor for PetInfo. You need to call the scanner for input several times before you call the constructor. See the code below:
private static void collectInfo(PetInfo[] info) {
Scanner input = new Scanner(System.in);
try {
for (int i = 0; i < info.length; i++) {
System.out.print("Enter pet name: ");
String petName = input.nextLine();
System.out.print("Enter pet type: ");
boolean petType = input.nextBoolean();
input.nextLine();
System.out.print("Enter pet breed: ");
String petBreed = input.nextLine();
System.out.print("Enter pet age: ");
double petAge = input.nextDouble();
input.nextLine();
System.out.print("Enter pet weight: ");
double petWeight = input.nextDouble();
input.nextLine();
System.out.print("Enter pet owner: ");
String petOwner = input.nextLine();
info[i] = new PetInfo(petName, petType, petBreed, petAge, petWeight, petOwner);
}
}
finally {
input.close();
}
}
Hopefully the code above gives you a good illustration of what I'm talking about. Also, don't forget to call input.nextLine() after calls to nextBoolean() and nextDouble(). Lastly, don't forget to close your input scanner to avoid a resource leak.
Hope that helps.
Well it's simple, when you input using scanner. It takes input in a string, since there is no such constructor which takes string as a parameter it is giving you an error.
You need to take the input from scanner in respective datatypes, store them in variables and then call the constructor. I think what you are trying to do is to call the constructor while taking comma separated input from the scanner, that's not possible.

Sum all double values of objects stored in ArrayList (Java)

I have an ArrayList that contains objects. Each of the object has 3 values: String name, double price, int quantity. How to write method that will sum all doubles of objects and print the result. And also if int quantity>1, price will be multiplied by quantity.
Code that i wrote so far:
Product class
public class Product {
private String name;
private double price;
private int quantity;
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public static Product createProduct(String name, double price, int quantity){
return new Product(name, price, quantity);
}
}
Product list class
import java.util.ArrayList;
import java.util.List;
public class ProductList {
private String name;
List<Product> newList;
public ProductList(String name) {
this.name = name;
this.newList = new ArrayList<>();
}
public boolean addNewProduct(Product product) {
if (findProduct(product.getName()) >= 0) {
System.out.println("Product is already on the list");
return false;
}
newList.add(product);
return true;
}
public boolean removeProduct(Product product) {
if (findProduct(product.getName().toUpperCase()) < 0) {
System.out.println("Product not found");
return false;
}
newList.remove(product);
return true;
}
private int findProduct(String productName) {
for (int i = 0; i < newList.size(); i++) {
Product product = newList.get(i);
if (product.getName().equals(productName)) {
return i;
}
}
return -1;
}
public Product queryProduct(String name) {
int position = findProduct(name);
if (position >= 0) {
return this.newList.get(position);
}
return null;
}
public double sumProducts() {
double sum = 0;
for (int i = 0; i < newList.size(); i++) {
sum += newList.get(i).getPrice();
}
return sum;
}
/*public boolean listProducts(){};
public boolean updateProduct(){};
*/
}
Simulation class:
public class Simulation {
private static Scanner scanner = new Scanner(System.in);
private static ProductList myProductList = new ProductList("My list");
private static void addNewProduct() {
System.out.println("Enter new product name: ");
String name = scanner.nextLine();
System.out.println("Enter new product price: ");
double price = scanner.nextDouble();
System.out.println("Enter new product quantity");
int quantity = scanner.nextInt();
Product newProduct = Product.createProduct(name, price, quantity);
if (myProductList.addNewProduct(newProduct) == true) {
System.out.println("New product added: " + name + " | price: " + price + " | quantity: " + quantity);
}
}
private static void removeProduct() {
System.out.println("Enter product name: ");
String name = scanner.nextLine().toUpperCase();
Product existingProduct = myProductList.queryProduct(name);
if (existingProduct == null) {
System.out.println("No such product");
return;
}
if (myProductList.removeProduct(existingProduct)) {
System.out.println("Sucessfully deleted product: " + existingProduct.getName());
} else {
System.out.println("Error deleting");
}
}
private static void printActions() {
System.out.println("Avaiable actions");
System.out.println("press: ");
System.out.println("0 - to shut down\n" +
"1 - to add new product\n" +
"2 - to remove product\n" +
"3 - to sum all products");
}
private static void sumProducts(){
myProductList.sumProducts();
}
public static void main(String[] args) {
printActions();
boolean quit = false;
while (!quit)
try {
System.out.println("\nEnter action: ");
int action = scanner.nextInt();
scanner.nextLine();
switch ((action)) {
case 0:
System.out.println("\nShutting down...");
quit = true;
break;
case 1:
addNewProduct();
break;
case 2:
removeProduct();
break;
}
} catch (InputMismatchException e) {
System.out.println("Bad key pressed, only values form 0 to 2 accepted");
scanner.nextLine();
}
}
}
Thanks in advance
You can do it in one line using Java 8.
public double sumProducts() {
return newList.stream().mapToDouble(product -> product.getPrice() * product.getQuantity()).sum();
}
If you use double to store the price, you will get incorrect answers when you try to add and multiply the values. For example, 0.1 + 0.2 is NOT the same double as 0.3. If you want accurate arithmetic for decimal numbers, you should use the BigDecimal class in place of double. If you don't do that, I can guarantee that your program will sometimes give wrong answers.
So you need to change your Product class as follows.
public class Product {
private String name;
private BigDecimal price;
private int quantity;
public Product(String name, BigDecimal price, int quantity) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public BigDecimal getPrice() {
return price;
}
public static Product createProduct(String name, BigDecimal price, int quantity){
return new Product(name, price, quantity);
}
}
You will also need to make corresponding changes in the code that calls the methods of this class.
Once you've done that, you can use the methods of the BigDecimal class to do arithmetic. It might look something like this.
public BigDecimal calculateTotalPrice() {
BigDecimal total = BigDecimal.ZERO;
for (Product product : newList) {
BigDecimal linePrice = product.getPrice().multiply(new BigDecimal(product.getQuantity()));
total = total.add(linePrice);
}
return total;
}
the sum of each product was missing multiply by its quantity.
public double sumProducts() {
double sum = 0;
for (int i = 0; i < newList.size(); i++) {
Product product = newList.get(i);
sum += product.getPrice() * product.getQuantity();
}
return sum;
}

How to create an Array in the constructor class?

I was create a book inventory program.
I has two classes one is the main class, and the other one is the constructor class name Item.
On the main class, i has create a array (Item[] book = new Item[100]) to store my input.
And in my Item class, i want to create a function below
public boolean addItem(Item[] iArray, String itemCode){
boolean c = false;
for(int i=0; i<iArray.length; i++){
if(iArray[i].getItemCode().equals(itemCode)){
c = true;
}
else{
c = false;
}
}
return c;
}
how to i make that Item[] iArray sync with the book array in main class?
public class Item {
private String itemCode;
private String description;
private int quantity;
private double costprice;
private double sellprice;
private String status = "Available";
private boolean check;
private double discount;
public Item(){
this("A000","default",0,0.00,0.00,0.25,"Available");
}
//construtor with parameter
public Item(String itemCode, String description, int quantity, double costprice, double sellprice, double discount, String status){
this.setItemCode(itemCode);
this.setDescription(description);
this.setQuantity(quantity);
this.setCostprice(costprice);
this.setSellprice(sellprice);
this.setStatus(status);
this.setDiscount(discount);
}
//setter and getter methods
public void setItemCode(String itemCode){
this.itemCode = itemCode;
}
public String getItemCode(){
return this.itemCode;
}
public void setDescription(String description){
this.description = description;
}
public String getDescription(){
return this.description;
}
public void setQuantity(int quantity){
this.quantity = quantity;
}
public int getQuantity(){
return this.quantity;
}
public void setCostprice(double costprice){
this.costprice = costprice;
}
public double getCostprice(){
return this.costprice;
}
public void setSellprice(double sellprice){
this.sellprice = sellprice;
}
public double getSellprice(){
return this.sellprice;
}
public void setStatus(String status){
this.status = status;
}
public String getStatus(){
return this.status;
}
public void setDiscount(double discount){
this.discount = discount;
}
public double getDiscount(){
return this.discount;
}
public void setCheck(boolean check){
this.check = check;
}
public boolean getCheck(){
return this.check;
}
public boolean addItem(Item[] iArray, String itemCode){
boolean c = false;
for(int i=0; i<iArray.length; i++){
if(iArray[i].getItemCode().equals(itemCode)){
c = true;
}
else{
c = false;
numberofobject++;
}
}
return c;
}
public void displaymenu(){
System.out.println("Menu");
System.out.println("1. Add New Item");
System.out.println("2. Search");
System.out.println("3. Edit Details");
System.out.println("4. Edit Quantity");
System.out.println("5. Stop Sell");
System.out.println("6. List");
System.out.println("7. Exit");
}*/
public String toString(){
String msg = "";
msg = this.getItemCode()+"\t\t\t\t"+this.getDescription()+"\t\t\t\t"+this.getQuantity()+"\t\t\t\t"+this.getCostprice()+"\t\t\t\t"+this.getSellprice()+"\t\t\t\t"+this.getDiscount()+"\t\t\t\t"+this.getStatus();
return msg;
}
this is my Item class.
import java.util.*;
public class Driver {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int choice,quantity,NOI=0;
double cprice,sprice,discount;
String itc,name,status = "Available";
boolean check = true;
Item[] book = new Item[100];
Scanner s1 = new Scanner(System.in);
do{
Item display = new Item();
display.displaymenu();
System.out.print("Please Select Menu: ");
choice = s1.nextInt();
if(choice==1){
do{
System.out.print("Please Enter the Item Code: ");
itc = s1.next();
//for(int i=0; i<book.length; i++){
//book[i].addItem(book, itc);
if(display.addItem(book, itc)==true){
System.out.println("the book item code already exist."+NOI);
check = false;
}
else
{
check = true;
} //This is the question where i faced.
//}
}while(check==false);
System.out.print("Please Enter the Description: ");
name = s1.next();
System.out.print("Please Enter the Quantity: ");
quantity = s1.nextInt();
System.out.print("Please Enter the Cost Price: ");
cprice = s1.nextDouble();
System.out.print("Please Enter the Sell Price: ");
sprice = s1.nextDouble();
System.out.print("Please Enter the Discount: ");
discount = s1.nextDouble();*/
book[NOI] = new Item(itc,name,quantity,cprice,sprice,discount,status);
NOI++;
}
when i add the second item, there was a error (Exception in thread "main" java.lang.NullPointerException),
how to solve it?
Your method does not do what you want, because even if you find the item code, the loop continues. You probably want something like this instead:
public boolean addItem(Item[] iArray, String itemCode){
for (Item item : iArray) {
if (item.getItemCode().equals(itemCode)) {
return true;
}
}
return false;
}
Note that the method you posted seems oddly named, because it does not add anything anywhere.
You might also consider using a List<Item> (ArrayList, etc.) instead of an Item[].
I am not sure I understand what you are looking for so if my answer is irrelevant just comment it and I will delete.
I assume you are trying to store information : add new item with its code to an array. But I'm not sure if you're:
trying to insure the uniqueness of your item in the array before inserting it:
maybe you can use a set of codes, it will simplify your problem, just check with .contains() and then add it or not
trying to add it to the list and if it already exist perform something (incrementation of the number of book for the code?)
maybe you can use a HashMap with code as key and book as item.
In your current state, your method addItem does not add anything, just return if your last book in the array matches your code...

Multiple classes: What am I doing wrong here?

I have officially come to the end of my rope. I cannot find what I did wrong. I have done this program almost exactly like another program I wrote a few days ago but I am having problems compiling. I do not know why I am getting errors on the output lines. Please help:
THIS IS THE RUNNING FILE:
package inventory1;
import java.util.Scanner;
public class RunApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DataCollection theProduct = new DataCollection();
String Name = "";
double pNumber = 0.0;
double Units = 0.0;
double Price = 0.0;
while (true) {
System.out.print("Enter Product Name: ");
Name = input.next();
theProduct.setName(Name);
if (Name.equalsIgnoreCase("stop")) {
return;}
System.out.print("Enter Product Number: ");
pNumber = input.nextDouble();
theProduct.setpNumber(pNumber);
System.out.print("Enter How Many Units in Stock: ");
Units = input.nextDouble();
theProduct.setUnits(Units);
System.out.print("Enter Price Per Unit: ");
Price = input.nextDouble();
theProduct.setPrice(Price);
System.out.print("\n Product Name: " + theProduct.getName());
System.out.print("\n Product Number: " + theProduct.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theProduct.getUnits());
System.out.print("\n Price per Unit: " + theProduct.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f\n\n\n", theProduct.getName(), theProduct.calculatePrice());
}
}
}
THIS IS THE DATA COLLECTIONS FILE:
package inventory1;
public class DataCollection {
String productName;
double productNumber, unitsInStock, unitPrice, totalPrice;
public DataCollection() {
productName = "";
productNumber = 0.0;
unitsInStock = 0.0;
unitPrice = 0.0;
}
// setter methods
public void setName(String name) {
productName = name;
}
public void setpNumber(double pNumber) {
productNumber = pNumber;
}
public void setUnits(double units) {
unitsInStock = units;
}
public void setPrice(double price) {
unitPrice = price;
}
// getter methods
public void getName(String name) {
productName = name;
}
public void getpNumber(double pNumber) {
productNumber = pNumber;
}
public void getUnits(double units) {
unitsInStock = units;
}
public void getPrice(double price) {
unitPrice = price;
}
public double calculatePrice() {
return (unitsInStock * unitPrice);
}
}
The reason why it doesn't compile is because your main code:
System.out.print("\n Product Name: " + theProduct.getName());
System.out.print("\n Product Number: " + theProduct.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theProduct.getUnits());
System.out.print("\n Price per Unit: " + theProduct.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f\n\n\n", theProduct.getName(), theProduct.calculatePrice());
Requires getName() But your getName() implementation did not exist. You didn't have the proper signature. Change it to a proper getter and it should work. Same goes for the other getters.
Instead of:
// getter methods
public void getName(String name) {
productName = name;
}
public void getpNumber(double pNumber) {
productNumber = pNumber;
}
public void getUnits(double units) {
unitsInStock = units;
}
public void getPrice(double price) {
unitPrice = price;
}
Use:
// getter methods
public String getName() {
return productName;
}
public double getpNumber() {
return productNumber;
}
public double getUnits() {
return unitsInStock;
}
public double getPrice() {
return unitPrice;
}
I believe the problem is in the way you are reading the values. While it is safe to read Strings using Scanner.next() but for other data structures you might need to clear a new line character from your input stream before you actually read the value.
But this is only in theory because you have given virtually nothing about your problem.

Categories