Why am I getting this "NoSuchMethodError" in my code? - java

Everytime I run my code, I get this error below
Exception in thread "main" java.lang.NoSuchMethodError: 'void Car.<init>(java.lang.String, java.lang.String, double, double, double)'
at DimaweaJeshuaAssignment11.setUpCars(DimaweaJeshuaAssignment11.java:48)
at DimaweaJeshuaAssignment11.main(DimaweaJeshuaAssignment11.java:11)
I looked to see if my constructor in my Car class was correct, and it was, but I'm stuck and can't figure out what the problem is. This is my code below
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class DimaweaJeshuaAssignment11 {
public static void main(String[] args) throws IOException {
// create an array of 5 Car objects
Car[] cars = new Car[5];
// set up the cars
setUpCars(cars);
// output the car details to file
writeCarDetailsToFile(cars);
// display the cars at the start of simulation
System.out.println("Cars at start of simulation");
printCars(cars);
int milesTraveled = 0;
boolean allCarsHaveGas = true;
// loop that continues until at least one of the cars has run out of gas
while(allCarsHaveGas) {
milesTraveled++; // increment the miles traveled
// loop to decrement the gallons after traveling 1 mile
for(int i=0;i<cars.length;i++) {
cars[i].updateFuel(1);
if(cars[i].getFuelGauge().getGallons() == 0) { // check if any of cars have run out of gas, update allCarsHaveGas to false
allCarsHaveGas = false;
}
}
}
// display the car details at the end of simulation
System.out.println("Cars at end of simulation");
printCars(cars);
// loop to display the first car that ran out of gas
for(int i = 0; i < cars.length; i++) {
if(cars[i].getFuelGauge().getGallons() == 0) {
System.out.println("\n"+cars[i].getOwner()+"'s car ran out of has after "+ milesTraveled +" miles");
break;
}
}
}
// method to set up the cars for the simulation based on the given information
public static void setUpCars(Car[] cars) {
cars[0] = new Car("Shrek", "Toyota Tundra", 15, 6, 20000);
cars[1] = new Car("Fiona", "Audi Q7", 21, 10, 8270);
cars[2] = new Car("Donkey", "Jeep CJ5", 14, 5, 11800);
cars[3] = new Car("Farquaad", "Smart Car", 42, 4, 710);
cars[4] = new Car("Dragon", "Chevy Suburban", 12, 30, 10800);
}
// method to display the details of the car in the array
public static void printCars(Car[] cars) {
System.out.println("----------------------------------------------------------------------------------------");
System.out.printf("%-20s%-20s%20s%20s\n","Owner","Brand","MPG","Current Gallons", "Mileage");
System.out.println("----------------------------------------------------------------------------------------");
for(int i=0;i<cars.length;i++)
System.out.printf("%-20s%-20s%20.2f%20.2f\n",cars[i].getOwner(),cars[i].getBrand(),cars[i].getFuelEconomy(),cars[i].getFuelGauge().getGallons(), cars[i].getMileage());
System.out.println();
}
// method to display the details of cars in the array to file
public static void writeCarDetailsToFile(Car[] cars) throws IOException {
// setup the file reference variable to refer to the text file
File filename = new File("Assignment11.txt");
// Create the file that the cars will be written to
PrintWriter resultsFile = new PrintWriter(filename);
// Write the details for each car to the file
for(int i=0;i<cars.length;i++) {
resultsFile.println(cars[i].getOwner());
resultsFile.println(cars[i].getBrand());
resultsFile.println(cars[i].getFuelEconomy());
resultsFile.println(cars[i].getFuelGauge().getGallons());
}
resultsFile.close();
}
}
class Car {
// attributes
private String owner;
private String brand;
private double milesPerGallon;
private FuelGauge fuelGauge;
private double mileage;
// constructor to initialize fields to specified values
public Car(String owner, String brand, double milesPerGallon, double gallons, double mileage) {
this.owner = owner;
this.brand = brand;
this.milesPerGallon = milesPerGallon;
fuelGauge = new FuelGauge();
fuelGauge.setGallons(gallons);
this.mileage = mileage;
}
// getters
public String getOwner() {
return owner;
}
public String getBrand() {
return brand;
}
public double getFuelEconomy() {
return milesPerGallon;
}
public FuelGauge getFuelGauge() {
return fuelGauge;
}
public double getMileage() {
return mileage;
}
// update the fuel of the car based on the miles traveled
public void updateFuel(double milesTraveled) {
double gallonsUsed = milesTraveled/milesPerGallon; // compute the gallons used for traveling milesTraveled
fuelGauge.decrementGallons(gallonsUsed); // decrement the gallons used
}
}
class FuelGauge {
// attribute
private double gallons;
// default constructor that initialize gallons to 0
public FuelGauge() {
}
// setter
public void setGallons(double gallons) {
this.gallons = gallons;
}
// getter
public double getGallons() {
return gallons;
}
// method to decrement the gallons by gallons used
public void decrementGallons(double gallonsUsed) {
if(gallonsUsed <= gallons) { // gallonsUsed <= gallons, decrement gallonsUsed from gallons
gallons -= gallonsUsed;
} else // gallonsUsed > gallons, set gallons to 0
gallons = 0;
}
}

Related

Pet BAG Assignment(Class file in Java)-Cannot run the program in Eclipse IDE through apporto

The image is the error message i get as well as showing the eclipse IDEThe problem I am having is I cant get my code to run through the eclipse IDE each time I click run it doesn't run and just gives me an error message "The selection cannot be launched, and there are no recent launches." I am trying to create a PET class file through java.
here is the code for my assignment:
import java.util.Scanner;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;
public class Pet {
private String petType;
private String petName;
private int petAge;
private Map<Pet, Integer> dogSpace; // contains the Pet and days it is staying
private Map<Pet, Integer> catSpace; // same but for cats
private int daysStay;
public double amountDue;
/**
* Pet, base class for Dog and Cat
* #param String name - Name of the Pet
* #param int age - Age of the Pet
* #param String type - Cat | Dog
*/
public Pet(String name, int age, String type) {
this.petName = name;
this.petAge = age;
this.petType = type;
this.dogSpace = new HashMap<Pet, Integer>(); // use a hashmap to keep track of pets in the shelter
this.catSpace = new HashMap<Pet, Integer>(); // the Pet object is the key, and the days they are staying is the value.
}
public void checkIn(Pet pet) {
Scanner in = new Scanner(System.in);
System.out.println("How many days will your " + this.petType + " be staying?");
int days = (int) in.nextInt();
this.daysStay = days;
switch(this.petType) {
case "Dog":
if(days > 1) {
System.out.println("Do you require grooming services?");
String needsGrooming = in.next();
boolean grooming;
if(needsGrooming.equals("yes") || needsGrooming.equals("y")) {
System.out.println("We will groom your dog...\n");
grooming = true;
}
else {
grooming = false;
}
this.checkInDog((Dog) pet, days, grooming); // handle the special dog cases
}
else {
this.checkInDog((Dog) pet, days, false);
}
break;
case "Cat":
if(this.catSpace.size() < 12) {
this.catSpace.put(pet, days);
}
break;
default: // Throw an exception if a pet other than a Cat | Dog is booked.
in.close(); // Close the scanner before exiting.
throw new RuntimeException("Sorry, we only accept cats and dogs");
}
in.close(); // Close the scanner when there is no exceptin thrown.
}
/**
* Contains extra steps for checking in a dog.
* #param pet - The dog object.
* #param days - Number of days staying.
* #param grooming - Whether or not the dog needs grooming.
*/
private void checkInDog(Dog pet, int days, boolean grooming) {
pet.setGrooming(grooming);
try {
if(this.dogSpace.size() < 30) { // Enforce the maximum of 30 dogs in the shelter.
this.dogSpace.put(pet, days);
pet.dogSpaceNbr = this.dogSpace.size() + 1;
pet.setDaysStay(days);
}
}
catch (Exception e) { // For some Map objects, calling size() on an empty collection can throw an error.
System.out.println("You're our first visitor!");
System.out.print(pet);
this.dogSpace.put(pet, days);
pet.dogSpaceNbr = 1;
}
System.out.println("" + pet.getPetName() + " will miss you, but is in good hands.");
}
/**
* Check out the desired Pet and calculate how much is owed for the boarding.
* #param pet - The pet you wish the check-out.
* #return amountDue - The amount of money owed for the boarding.
*/
public double checkOut(Pet pet) {
double fee;
if(pet.getPetType() == "Dog") {
double groomingfee = 0.0;
Dog animal = (Dog) pet;
int days = this.dogSpace.remove(pet);
double weight = animal.getDogWeight();
if(weight < 20) {
fee = 24.00;
if(animal.getGrooming()) {
groomingfee = 19.95;
}
} else if (weight > 20 && weight < 30) {
fee = 29.00;
if(animal.getGrooming()) {
groomingfee = 24.95;
}
} else {
fee = 34.00;
if(animal.getGrooming()) {
groomingfee = 29.95;
}
}
System.out.println("Fee Schedule:\n Boarding Fee: " + (fee*days) + "\nGrooming Fee: " + groomingfee);
animal.amountDue = (fee * days) + groomingfee;
return animal.amountDue;
}
else {
int days = this.catSpace.remove(pet);
fee = 18.00;
pet.amountDue = (fee * days);
return pet.amountDue;
}
}
public Pet getPet(Pet pet) { // Not sure why we need this.
return pet;
}
public Pet createPet(String name, int age, String type) {
switch(type) {
case "Dog":
return new Dog(name, age);
case "Cat":
return new Pet(name, age, "Cat"); // I have implemented the dog class, not the cat.
default:
throw new Error("Only Dogs and Cats can stay at this facility.");
}
}
/**
* Asks the user to fill in all of the attributes of a pet. Saves them directly to the object it was called on.
* #param pet - The pet you wish to update information on.
*/
public void updatePet(Pet pet) {
Scanner in = new Scanner(System.in);
System.out.println("What is the pets new name?");
pet.setPetName(in.next());
System.out.println("What is the pets age?");
pet.setPetAge(in.nextInt());
System.out.println("What type of animal is your pet?");
pet.setPetType(in.next());
in.close();
}
public String getPetName() {
return this.petName;
}
public int getPetAge() {
return this.petAge;
}
public String getPetType() {
return this.petType;
}
public void setPetName(String name) {
this.petName = name;
}
public void setPetAge(int age) {
this.petAge = age;
}
public void setPetType(String type) {
switch(type) { // while a switch is extra here, it will make it easier to add other pets.
case "Dog":
this.petType = type;
break;
case "Cat":
this.petType = type;
break;
}
}
public void setDaysStay(int days) {
this.daysStay = days;
}
}
public class Dog extends Pet {
public int dogSpaceNbr;
private double dogWeight;
private boolean grooming;
public Dog(String name, int age) { // automatically declares a pet of type Dog
super(name, age, "Dog"); // super is used to call the parent classes constructor
}
public double getDogWeight() {
return this.dogWeight;
}
public boolean getGrooming() {
return this.grooming;
}
public void setDogWeight(double weight) {
this.dogWeight = (double) weight; // casting a double here might be redundant, but it helps us to be sure
} // we don't get at type error
public void setGrooming(boolean value) {
this.grooming = value;
}
}
public class Cat extends Pet {
private int catSpaceNbr; // The number space the cat is in.
public Cat(String name, int age) { // automatically declares a pet of type Cat
super(name, age, "Cat"); // Calls the constructor of the parent class
}
public int getCatSpace() {
return this.catSpaceNbr;
}
public void setCatSpace(int number) {
this.catSpaceNbr = number;
}
}type here
I haven't tried much to fix the issue besides look up videos and now reach out for help just not sure what to do.
In the Package Exporer or Navigator tab (right hand panel) right-click on the class that contains public static void main and choose Run as >> Java application.
When you have done that successfully you can run with the run button.

baby's first classes and methods in java

Okay so working on my first assignment for my introduction to Java class. I have read the first 2 chapters in the book probably 6 times now and I've looked at a dozen various tutorials online and I'm still not getting what the problem is here.
I have class Student
//declare main class
public class Student {
// declare variables needed including ID_number, Credit_hours, points and GPA
private float ID_number;
private int Credit_hours;
private int points;
public float GPA;
// methods will go here
//method to return ID number
public float getID_number()
{
return ID_number;
}
//method to set the ID number
public void setID_number(float ID_number)
{
ID_number = ID_number;
}
//method to return credit hours
public int getCredit_hours()
{
return Credit_hours;
}
//method to set credit hours
public void setCredit_hours(int Creds)
{
Credit_hours = Creds;
}
//method to get points
public int getpoints()
{
return points;
}
//method to set points
public void setpoints(int points)
{
points = points;
}
//method to calculate and return GPA
public float setGPA()
{
GPA = points/Credit_hours;
//return GPA;
}
//method to print the GPA
public float getGPA(float GPA)
{
return GPA;
}
}
and then I have the class ShowStudent which is supposed to instantiate the Student Class:
import java.util.Scanner;
class ShowStudent
{
public static void main (String args[])
{
Student newStudent;
newStudent = getStudentInfo();
displayStudent(newStudent);
}
public static Student getStudentInfo()
{
Student tempStu = new Student();
float ID_number;
int Credit_hours;
int points;
Scanner input = new Scanner(System.in);
System.out.print("Enter Student ID Number >> ");
ID_number = input.nextFloat();
tempStu.setID_number(ID_number);
}
public static void displayStudent(Student aStu)
{
System.out.println("\nStudnet number is: #" + aStu.getID_number() +
" While their GPA is " + aStu.getGPA());
}
}
but eclipse is throwing all kinds of errors at me including the following:
"method must return type student" line 12 in showStudent
"Method getGPA is not applicable for this argument" Line 28 in showStudent
I just do not understand what is the problem here and I'm getting super frustrated with this.
Firsly you getStudentInfo() must return a Student object like this
public static Student getStudentInfo()
{
Student tempStu = new Student();
float ID_number;
int Credit_hours;
int points;
Scanner input = new Scanner(System.in);
System.out.print("Enter Student ID Number >> ");
ID_number = input.nextFloat();
tempStu.setID_number(ID_number);
return tempStu;
}
And secondly, you miseed up your getters and setters and some variable implementations in your student class. It should be like this
public class Student {
// declare variables needed including ID_number, Credit_hours, points and GPA
private float ID_number;
private int Credit_hours;
private int points;
public float GPA;
// methods will go here
//method to return ID number
public float getID_number()
{
return ID_number;
}
//method to set the ID number
public void setID_number(float ID_number)
{
this.ID_number = ID_number;
}
//method to return credit hours
public int getCredit_hours()
{
return Credit_hours;
}
//method to set credit hours
public void setCredit_hours(int Creds)
{
Credit_hours = Creds;
}
//method to get points
public int getpoints()
{
return points;
}
//method to set points
public void setpoints(int points)
{
this.points = points;
}
//method to calculate and return GPA
public float getGPA()
{
return GPA;
}
//method to print the GPA
public void setGPA(float GPA)
{
this.GPA = GPA;
}
}

Subclasses and Superclasses

I'm trying to build a program that has certain requirements, the main being I have a class, and then make a subclass that adds a feature. I create the class DVD, and then I create the subclass.
I'm adding a method to add the year to the list, as well as a restocking fee which will be added to the final inventory value that prints. I built the subclass, created the overriding methods, but it is not being added to the output displayed. Not only that, but it is placing the input year in the wrong place. I am not getting any errors, it just acts like the subclass doesn't exist, even though my DVD class says that some of the methods are being overridden.
I'm thinking I must be missing something where I am supposed to call the new method, and maybe I read the resource wrong, but it sounded like I only needed to call the DVD class, and the methods I wanted overridden would be overridden automatically. I'd prefer to just add this information to the superclass, but it is a requirement for an assignment.
So I'm wondering how do I actually go about calling these override methods when I need them to add these new features? I keep seeing resources telling me how to create them, but not actually implement them.
From my main method, I call the dvd class and then print it. however, it only prints what's in the original dvd class, except for the odd addition of adding the year to where the product ID should be.
public class DVD {
String name;
int id;
int items;
double cost;
//default constructor
public DVD() {
name = "";
id = 0;
items = 0;
cost = 0.0;
}//end default constructor
//constructor to initialize object
public DVD(String dvdName, int itemNum, int quantity, double price) {
name = dvdName;
id = itemNum;
items = quantity;
cost = price;
}//end constructor
//method to calculate value
public double getInventoryValue() {
return items * cost;
}
//method to set name
public void setdvdName(String dvdName){
this.name = dvdName;
}
//method to get name
public String getName(){
return name;
}
//method to set id
public void setitemNum( int itemNum){
this.id = itemNum;
}
//method to get id
public int getId(){
return id;
}
//method to set items
public void setquantity(int quantity){
this.items = quantity;
}
//method to get items
public int getItems(){
return items;
}
//method to set cost
public void setprice( double price){
this.cost = price;
}
//method to get cost
public double getCost(){
return cost;
}
/**
*
* #return
*/
public String toString() {
return "DVD Name: " + getName() +
"ID: " + getId() +
"Items: " + getItems() +
"Cost: " + getCost() +
"Total Value: " +getInventoryValue();
}
}
-
public class ExtendedDVD extends DVD{
double restockFee;
int year;
public ExtendedDVD(){
year = 0;
}
public ExtendedDVD(int year) {
this.year = year;
}
public void setRestockFee(){
this.restockFee = 0.05;
}
public double getRestockFee(){
return restockFee;
}
public void setYear(){
this.year = 0;
}
public int getYear(){
return year;
}
#Override
public double getInventoryValue(){
double value1 = super.getInventoryValue();
double value = restockFee * value1;
double totalInventoryValue = value + super.getInventoryValue();
return totalInventoryValue;
}
#Override
public String toString(){
return super.toString() + "Year" + getYear();
}
}
}
public class Inventory {
DVD[] inventory = new DVD[5];
int current = 0;
private int len;
public Inventory(int len){
inventory = new DVD[len];
}
public double calculateTotalInventory() {
double totalValue = 0;
for ( int j = 0; j < inventory.length; j++ )
totalValue += inventory[j].getInventoryValue();
return totalValue;
}
/**
*
* #param dvd
* #throws Exception
*/
public void addDVD(DVD dvd) throws Exception {
if (current < inventory.length) {
inventory[current++]=dvd;
}else {
Exception myException = new Exception();
throw myException;
}
}
void sort() {
for (DVD inventory1 : inventory) {
len = current;
}
for (int i=0; i<len;i++) {
for(int j=i;j<len;j++) {
if (inventory[i].getName().compareTo(inventory[j].getName())>0) {
DVD temp = inventory[j];
inventory[j] = inventory[i];
inventory[i] = temp;
}
}
}
}
public int getNumberOfItems() {
return current;
}
public void printInventory() {
System.out.println("Current Inventory:");
for(int i=0;i<current;i++) {
System.out.println(inventory[i]);
}
System.out.println("The total value of the inventory is:"+calculateTotalInventory());
}
}
-
public class inventoryprogram1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
boolean finish = false;
String dvdName;
int itemNum;
int quantity;
double price;
int year = 0;
Inventory inventory = new Inventory(5);
while (!finish) {
Scanner input = new Scanner(System.in); // Initialize the scanner
System.out.print("Please enter name of DVD: ");
dvdName = input.nextLine();
if (dvdName.equals("stop")) {
System.out.println("Exiting Program");
break;
} else {
System.out.print("Please enter Product Number: ");
itemNum = input.nextInt();
System.out.print("Please enter units: ");
quantity = input.nextInt();
System.out.print("Please enter price of DVD: ");
price = input.nextDouble();
System.out.print("Please enter production year: ");
itemNum = input.nextInt();
DVD dvd= new DVD(dvdName,itemNum,quantity,price);
try {
inventory.addDVD(dvd);
}catch( Exception e) {
System.out.println("Inventory is full.");
break;
}
System.out.println("DVD: " + dvd);
}//end else
}
inventory.sort();
inventory.printInventory();
}
}
if you want to use the new methods that you wrote in ExtendedDVD you need to instantiate that class you are still calling the original dvd class so you will still get those methods.
for example
DVD dvd = new DVD(dvdName, itemNum, quantity, price);
and
DVD Dvd = new ExtendedDVD(dvdName, itemNum, quantity, price);
are two different things
also if you look in your main method you are assigning itemNum twice that is why it is showing you the year
In the main method you just instantiate a DVD object, not an ExtendedDVD object.
replace
DVD dvd= new DVD(dvdName,itemNum,quantity,price);
by something like
DVD dvd= new ExtendedDVD(year);
And obviously, you may want another constructor in ExtendedDVD

Why will objects now be created from my class

An error points to the word "new" when I try to compile this program. I'm trying to create 2 objects from the carOrder class and I'm havin troubles! I've had this problem with other programs before and I'm not sure why and it's killing me, please help!
import java.text.DecimalFormat;
import java.util.Scanner;
public class CarOrder
private String buyer;
private String carType;
private double cost;
private int quantity;
private boolean taxStatus;
private double discountedCost;
private double taxAmount;
// Default Constructor
public void carOrder()
{
}
// Constructor
public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
buyer = buy;
carType = car;
cost = cos;
quantity = quan;
taxStatus = tax;
}
// Sets the company buying cars
public void setBuyer(String buy)
{
buyer = buy;
}
// Sets the car type being purchased
public void setCarType(String car)
{
carType = car;
}
// Sets cost of the cars being purchased
public void setCost(double cos)
{
cost = cos;
}
// Sets the quantity of cars being purchased
public void setQuantity(int quan)
{
quantity = quan;
}
// Sets tax status for the cars
public void setTaxStatus(boolean tax)
{
taxStatus = tax;
}
// Returns name of buyer to user
public String getBuyer()
{
return buyer;
}
// Returns type of car to user
public String getCarType()
{
return carType;
}
// Returns cost to user
public double getCost()
{
return cost;
}
// Returns quantity of cars to user
public int getQuantity()
{
return quantity;
}
// Returns tax status to user
public boolean getTaxStatus()
{
return taxStatus;
}
// Returns discounted cost to user
public double getDiscountedCost()
{
if (quantity > 10)
if (quantity > 20)
discountedCost = cost - cost * .10;
else
discountedCost = cost - cost * .05;
else
discountedCost = cost;
return discountedCost;
}
// Returns tax amount to users
public double getTaxAmount()
{
taxAmount = cost * .0625;
return taxAmount;
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
CarOrder speedy = new CarOrder("Speedy Rental", "Mini Cooper", 22150, 15, true);
CarOrder zip = new CarOrder("Zip Car Co.", "Ford Fusion", 27495, 6, true);
System.out.println("Enter first Buyer");
String buyer1 = keyboard.nextLine();
}
}
public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
should be
public CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
Constructor's don't have a return type, not even void.
Currently, you have a method named CarOrder in your class as it has a return type as void, which voilates the rules of custructor. If you remove void, then it'd a constructor as it has the same name as your class.
Same applies to your constructor with no-argsaswell.
public void CarOrder()
should be
public CarOrder()
you are missing a "{" right after public class CarOrder ... :)
When you don't declare a constructor, Java provides a default constructor that have no arguments. As you declared CarOrder(String buy, String car, double cos, int quan, boolean tax), the default constructor is not created anymore. You made a method called carOrder, that probably was an attempt to make a constructor with no arguments, but it has two problems:
it has a return type (void) and constructor doesn't have one
the name is different from the class (cardOrder isn't the same as CarOrder, since Java is case sensitive)
If you want to make a new CarOrder() call, just add the following code:
public CarOrder() {
//insert your implementation here
}
A constructor with a return type is treated as a method by the compiler.

Java Error: Cannot find symbol/Inventory Program [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm new to Java and trying to compile this inventory program. I keep getting the same error message and can't figure out what I'm missing. The error is cannot find symbol and it is on lines 10,18,20,21,22,23 anyting that says Inventory has the ^ symbol pointing at them. I am enclosing what I have racked my brains and tried everything I can and would appreciate any help with this.
//InventoryProgram2.java
//Camera inventory program
import java.util.Arrays;
public class InventoryProgram2
{
public static void main( String args [])
{
//instantiate camera object
Inventory myInventory = new Inventory();
//displays welcome message
System.out.println( "Camera Invenotry Program");
System.out.println();//skips a line
//create and initialize an array of Cameras
Inventory[] Camera = new Inventory[4];
Camera[0] = new Inventory( 1980, "Cannon Rebel T3", 20, 489.99);
Camera[1] = new Inventory( 2120, "Nikon CoolPix L810", 5, 279.99);
Camera[2] = new Inventory( 1675, "Sony CyberShot HX200V", 12, 479.99);
Camera[3] = new Inventory( 1028, "Fujifilm FinePix S4300", 3, 199.99);
//for each array element, output value
for(int count = 0; count < Camera.length; count++)
{
Camera[count] = count+1;
System.out.printf("Product Number: %4.2f\n", Camera[count].getprodNumber() );
System.out.printf("Product Name: %s\n", Camera[count].getprodName() );
System.out.printf("Units In Stock: %.2f\n", Camera[count].getunitsTotal() );
System.out.printf("Unit Price: $%4.2f\n", Camera[count].getunitPrice() );
System.out.printf("Inventory Value: $%4.2f\n", Camera[0].gettotalInventory() );
System.out.println();//blank line to seperate products
}//end for
}//end main method
}//end public class InventoryProgram2
class Camera
{
private int prodNumber;//product number
private String prodName;//product name
private int unitsTotal;//total units in stock
private double unitPrice;//price per unit
private double totalInventory;//amount of total inventory
//initializa four-argument constructor
public Camera ( int number, String name, int total, double price)
{
prodNumber = number;
prodName = name;
setUnitsTotal (total);//validate and store total of camera
setUnitPrice (price);//validate and store price per camera
}//end four-argument constructor
public void setProdNumber (int number)
{
prodNumber = number;
}
public int getProdNumber()
{
return prodNumber;
}
public void setProdName (String name)
{
prodName = name;
}
public String getProdName()
{
return prodName;
}
public void setUnitsTotal (int total)
{
unitsTotal = total;
}
public int getUnitsTotal()
{
return unitsTotal;
}
public void setUnitPrice (double price)
{
unitPrice = price;
}
public double getUnitPrice()
{
return unitPrice;
}
// method to set Inventory value
//public void setInventoryValue(double value)
//{
//InventoryValue = value;
//}end method setInventoryValue
//method to get InventoryValue
//public double getInventoryValue()
//{
// return InventoryValue;
//} //end method to getInventoryValue
public double getInventoryValue()
{
return unitPrice * unitsTotal;
}//end method to getInventoryValue
//method to set TotalInventory
//public void setTotalInventory(double value)
//{
//TotalInventory = total;
//}end method setTotalInventory
//method to get TotalInventory
//public double getTotalInventory()
//{
//return TotalInventory;
//}end method to getTotalInventory
}//end class Camera
I needed to keep one class camera so I did some adjustemnts. I'm down to 7 errors as follows:
line 10: error: constructor Camera in class Camera cannot be applied to given types;
Camera myCamera = new Camera();
required: int,String,int,double
found: no arguments
reason: actual and formal argument lists differ in length
line 29: error: incompatible types
Inventory[count] = count+1
^
required: Camera
found: int
lines 31, 32, 33, 34, 35, : error cannot find symbol
System.out.printf(......) [count].getprodNumber
^
symbol: method getprodNumber()
location: class Camera
here is my updated code:
//Inventory.java
//Camera inventory program
import java.util.Arrays;
public class Inventory
{
public static void main( String args [])
{
//instantiate camera object
Camera myCamera = new Camera();
//displays welcome message
System.out.println( "Camera Invenotry Program");
System.out.println();//skips a line
//create and initialize an array of Cameras
Camera[] Inventory = new Camera[4];
Inventory[0] = new Camera( 1980, "Cannon Rebel T3", 20, 489.99);
Inventory[1] = new Camera( 2120, "Nikon CoolPix L810", 5, 279.99);
Inventory[2] = new Camera( 1675, "Sony CyberShot HX200V", 12, 479.99);
Inventory[3] = new Camera( 1028, "Fujifilm FinePix S4300", 3, 199.99);
//for each array element, output value
for(int count = 0; count < Inventory.length; count++)
{
Inventory[count] = count+1;
System.out.printf("Product Number: %4.2f\n", Inventory[count] .getprodNumber() );
System.out.printf("Product Name: %s\n", Inventory[count] .getprodName() );
System.out.printf("Units In Stock: %.2f\n", Inventory[count] .getunitsTotal() );
System.out.printf("Unit Price: $%4.2f\n", Inventory[count] .getunitPrice() );
System.out.printf("Inventory Value: $%4.2f\n", Inventory[0] .gettotalInventory() );
System.out.println();//blank line to seperate products
}//end for
}//end main method
}//end public class Inventory
class Camera
{
private int prodNumber;//product number
private String prodName;//product name
private int unitsTotal;//total units in stock
private double unitPrice;//price per unit
private double totalInventory;//amount of total inventory
//initializa four-argument constructor
public Camera ( int number, String name, int total, double price)
{
prodNumber = number;
prodName = name;
setUnitsTotal (total);//validate and store total of camera
setUnitPrice (price);//validate and store price per camera
}//end four-argument constructor
public void setProdNumber (int number)
{
prodNumber = number;
}
public int getProdNumber()
{
return prodNumber;
}
public void setProdName (String name)
{
prodName = name;
}
public String getProdName()
{
return prodName;
}
public void setUnitsTotal (int total)
{
unitsTotal = total;
}
public int getUnitsTotal()
{
return unitsTotal;
}
public void setUnitPrice (double price)
{
unitPrice = price;
}
public double getUnitPrice()
{
return unitPrice;
}
// method to set Inventory value
//public void setInventoryValue(double value)
//{
//InventoryValue = value;
//}end method setInventoryValue
//method to get InventoryValue
//public double getInventoryValue()
//{
// return InventoryValue;
//} //end method to getInventoryValue
public double getInventoryValue()
{
return unitPrice * unitsTotal;
}//end method to getInventoryValue
//method to set TotalInventory
//public void setTotalInventory(double value)
//{
//TotalInventory = total;
//}end method setTotalInventory
//method to get TotalInventory
//public double getTotalInventory()
//{
//return TotalInventory;
//}end method to getTotalInventory
}//end class Camera
It looks like your Camera class should really be called Inventory. You're using Camera in your main application class as a variable name not as a type.
Change class Camera to class Inventory
and
public Camera ( int number, String name, int total, double price)
to
public Inventory ( int number, String name, int total, double price)
and it should get you closer, if not all the way there.
Check if Inventory class is in the same package as that of this class. Else just import that class like you did for Arrays.

Categories

Resources