baby's first classes and methods in java - 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;
}
}

Related

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

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;
}
}

I am trying to figure out why my class payroll is not adding all the salaries properly....help me find the bug

So I am working on this Payroll class, I need to create two employees, hours worked and hourly pay and the calculate salaries. Finally, I have to add 10 extra hours to one of the previously created employees and calculate and display the total payroll. I wrote the two classes and everything works perfect, but when I look at the total Payroll it does not take into consideration the added hours.
The output for totalPayRoll should be $2000 after increasing the hours but i still get $1750!
public class PayRoll {
static double getTotalPayRoll()
{
return TotalPayRoll;
}
public String employeeId;
public int hoursWorked;
public final double hourlyPay;
private static double TotalPayRoll;
private static double Salary;
public PayRoll (String theEmployeeId, int theHoursWorked,
double theHourlyPay)
{
this.employeeId = theEmployeeId;
this.hoursWorked = theHoursWorked;
this.hourlyPay = theHourlyPay;
Salary = hoursWorked*hourlyPay;
TotalPayRoll = TotalPayRoll + Salary ;
}
public String getTheEmployeeId()
{
return this.employeeId;
}
public int getTheHoursWorked()
{
return this.hoursWorked;
}
public double getTheHourlyPay()
{
return this.hourlyPay;
}
public double getSalary()
{
return PayRoll.Salary;
}
public void increase (int extraHours)
{
hoursWorked = (hoursWorked + extraHours);
}
public void changeTheHoursWorked (int amount)
{
hoursWorked = hoursWorked + amount;
}
public void calculateSalary()
{
Salary = hoursWorked*hourlyPay;
}
public void calculateTotalPayRoll()
{
TotalPayRoll= TotalPayRoll+Salary;
}
public void changeHours(int newHours)
{
hoursWorked = newHours;
}
}
And this is the main
public class Test {
public static void main(String[] args) {
// TODO code application logic here
Date d = new Date();
DateFormat df = DateFormat.getDateInstance( DateFormat.MEDIUM );
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("\nPayroll For Week Ending " + df.format(d));
System.out.println("-------------------------------------");
PayRoll employee1 = new PayRoll("444-4444", 30, 25);
employee1.calculateSalary();
displaySalary(employee1, nf);
PayRoll employee2 = new PayRoll("555-5555", 20, 50);
employee2.calculateSalary();
displaySalary(employee2, nf);
System.out.println("Increase " + employee1.getTheEmployeeId() +
" by 10 hours");
employee1.changeTheHoursWorked(10); // 10 hours increase
employee1.calculateSalary();
displaySalary(employee1, nf);
System.out.println("Total payout amount.. " +
nf.format(PayRoll.getTotalPayRoll()));
}
public static void displaySalary(PayRoll e, NumberFormat nf)
{
System.out.println("Employee #: " + e.getTheEmployeeId());
System.out.println("Hours Worked: " + e.getTheHoursWorked());
System.out.println("Hourly Rate: " + e.getTheHourlyPay());
System.out.println("Your Salary is: " + e.getSalary());
System.out.println("---------------------------------\n");
}
}
In your class :
private static double TotalPayRoll;
private static double Salary;
Both are static members(class level members), so there will be only one copy of these members which will be shared among all the objects. Because TotalPayRoll and salary should be different for different payrolls so these should be non-static.
This is because you have static fields - make everything non-static
private static double TotalPayRoll; -> private double TotalPayRoll;
private static double Salary; -> private double Salary;
What is happening with static fields is
Firstly hoursWorked is set to 30
then
hoursWorked is set to 20
then
hoursWorked is increased by 10
Since you are declaring objects of your PayRoll class, you don't need to make an static members.
You can make your class like this
public class PayRoll {
//don't have to declare any member public since you have functions to return value
//don't need access specifier since they are private by default
String employeeId;
int hoursWorked;
double hourlyPay;
double TotalPayRoll=0; //you have to initialize it to zero
double Salary;
public PayRoll (String theEmployeeId, int theHoursWorked,
double theHourlyPay)
{
this.employeeId = theEmployeeId;
this.hoursWorked = theHoursWorked;
this.hourlyPay = theHourlyPay;
// Salary = hoursWorked*hourlyPay;
// TotalPayRoll = TotalPayRoll + Salary ;
//you do not need to do this since you have different functions for them
}
public double getTotalPayRoll()
{
return this.TotalPayRoll;
}
public String getTheEmployeeId()
{
return this.employeeId;
}
public int getTheHoursWorked()
{
return this.hoursWorked;
}
public double getTheHourlyPay()
{
return this.hourlyPay;
}
public double getSalary()
{
return this.Salary;
}
//don't need the increase method
public void changeTheHoursWorked (int amount)
{
hoursWorked += amount;
}
public void calculateSalary()
{
Salary = hoursWorked*hourlyPay;
}
public void calculateTotalPayRoll()
{
TotalPayRoll+=Salary;
}
//don't need the change hours function
}
Hope this helps :)

how to use abstract classes, and implementing them

I'm not sure how eloquently I can really explain what I don't understand/need help with, I'm still Very new to Object Oriented Programming. This is regarding my coursework and I don't expect anyone to do it for me, I just need help understanding how to move on, and if I'm even on the right track.
Ok, so on to my question. Basically, I am attempting to create an arraylist which will hold a few objects which themselves has a bunch of information(obviously), my spec said to create an abstract class, which will be extended by my constructor class, which I did. The abstract class has a few variables (decided by spec) But I dont know how to move them over to my extended class.
I'll post my code below, and I hope it makes sense. I'd be very thankful for any help you all could provide. I'm very confused right now.
Basically, I would love to know, A) How do I create an object in my arraylist which will be able to contain everything in SportsClub and FootballClub, and preferably all the variables user inputted.
And B) I don't know how to print The object, When I print right now I get coursework.FootballClub#49233bdc, Which I'm sure there's a reason for but I need the information in the objects to display, E.g. name. And if possible to sort the results by alphabetical order with respect to name? I hope this is all written ok. Sorry and Thank you in advance.
package coursework;
import java.util.*;
/**
*
* #author w1469384
*/
public class PremierLeagueManager implements LeagueManager{
public static void main(String[] args) {
Scanner c1 = new Scanner(System.in);
Scanner c2 = new Scanner(System.in);
ArrayList<FootballClub> PL = new ArrayList<FootballClub>();
int choice;
System.out.println("Enter 1; To create a club, 2; To Delete a Club, 3; To display all clubs and 99 to close the program");
choice = c1.nextInt();
//Creates and adds a new FootballClub Object
while (choice != 99){
if (choice == 1){
System.out.println("Please Enter The games played for the club");
int played = c1.nextInt();
System.out.println("Please enter the number of wins");
int wins = c1.nextInt();
System.out.println("please enter the number of losses");
int losses = c1.nextInt();
System.out.println("please enter the number of draws");
int draws = c1.nextInt();
System.out.println("please enter the number of goals for");
int goalsFor = c1.nextInt();
System.out.println("please enter the number of goals against");
int goalsAgainst = c1.nextInt();
FootballClub club = new FootballClub(played, wins, losses, draws, goalsFor, goalsAgainst);
PL.add(club);
System.out.println("check");
}
//Deletes a FootballClub Object
if (choice == 2){
}
//Displays all Football Clubs in the PremierLeague array
if (choice == 3){
System.out.println(PL);
}
//Closes the Program 1
choice = c1.nextInt();
}
}
}
public abstract class SportsClub {
public String name;
public String location;
public int capacity;
public void setName(String Name){
name = Name;
}
public void setLocation(String Location){
location = Location;
}
public void setCapacity(int Capacity){
capacity = Capacity;
}
public String getName(){
return name;
}
public String getLocation(){
return location;
}
public int getCapacity(){
return capacity;
}
}
public class FootballClub extends SportsClub {
//Statistics for the club.
int played;
int wins;
int losses;
int draws;
int goalsFor;
int goalsAgainst;
public FootballClub(int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst){
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
public void setPlayed(int newPlayed){
played = newPlayed;
}
public void setWins(int newWins){
wins = newWins;
}
public void setLosses(int newLosses){
losses = newLosses;
}
public void setDraws(int newDraws){
draws = newDraws;
}
public void setGoalsFor(int newGoalsFor){
goalsFor = newGoalsFor;
}
public void setGoalsAgainst(int newGoalsAgainst){
goalsAgainst = newGoalsAgainst;
}
public int getPlayed(){
return played;
}
public int getWins(){
return wins;
}
public int getLosses(){
return losses;
}
public int getDraws(){
return draws;
}
public int getGoalsFor(){
return goalsFor;
}
public int getGoalsAgainst(){
return goalsAgainst;
}
}
FootballClub inherits the variables declared in SportsClub so you can set them as you please.
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
// set the variables from the superclass
name = inName;
location = inLocation;
capacity = inCapacity;
}
FootballClub also inherits the methods declared in SportsClub so you can use the setters and getters too.
Normally you would create a constructor for SportsClub that sets these and then call that constructor from the FootballClub constructor.
// in SportsClub
protected SportsClub(
String inName, String inLocation, int inCapacity
) {
name = inName;
location = inLocation;
capacity = inCapacity;
}
// in FootballClub
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
super(inName, inLocation, inCapacity);
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
You should also make your member variables protected or private if you are using setters and getters.
I don't know how to print The object
You need to override toString. There is a short tutorial here.
Also unrelated side note: all Java variable identifiers should start with a lowercase letter.
When you have a method like this:
public void setName(String Name) { name = Name; }
It should be:
public void setName(String inName) { name = inName; }
Or:
public void setName(String name){ this.name = name; }

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

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