Im trying to get help with to run with my automobile compiler I chaned a few things and i have 1 error
public class AutomobileDescription
{
/**
Constructor to display the make, model and price the new automobile I wish to purchase
*/
public AutomobileDescription(String carMake, String carModel, carPrice)
{
make = m;
model = mo;
price = p;
}
public String m =("Toyota");
public String mo =("Camry");
public String p =("22055");
public String getAutomobileinfo()
{
return m + mo + p;
Automobile myAutomobile = new Automobile(Toyota, Camry, 22055);
System.out.println("The Make, Model and Price of the car is: m + mo + p ");
}
}
----jGRASP exec: javac -g AutomobileDescription.java
AutomobileDescription.java:7: error: expected
public AutomobileDescription(String carMake, String carModel, carPrice)
^
1 error
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
You have multiple problems here:
public class AutomobileDescription
{
/**
Constructor to display the make, model and price the new automobile I wish to purchase
*/
public AutomobileDescription(String carMake, String carModel, /*no return type*/ carPrice)
{
make = m;
model = mo;
price = p;
}
public String m =("Toyota");
public String mo =("Camry");
public String p =("22055");
public String getAutomobileinfo()
{
return m + mo + p; /*return? then why statements after this?*/
Automobile myAutomobile = new Automobile(Toyota, Camry, 22055);
System.out.println("The Make, Model and Price of the car is: m + mo + p ");
}
}
Solution:
public class AutomobileDescription{
/**
Constructor to display the make, model and price the new automobile I wish to purchase
*/
public AutomobileDescription(String carMake, String carModel, String carPrice)
{
m = make;
mo = model;
p = carPrice;
}
private String m;
private String mo;
private String p;
public String getAutomobileinfo()
{
return m + mo + p;
}
public static void main(String[] args){
AutomobileDescription myAutomobile = new AutomobileDescription("Toyota", "Camry", "22055");
System.out.println("The Make, Model and Price of the car is: " + myAutomobile.getAutomobileinfo());
}
}
public AutomobileDescription(String carMake, String carModel, carPrice)
^^^^^^^^
You have omitted the type of parameter carPrice. Most likely you want
public AutomobileDescription(String carMake, String carModel, BigDecimal carPrice)
Another problem...
public String getAutomobileinfo()
{
return m + mo + p;
Automobile myAutomobile = new Automobile(Toyota, Camry, 22055);
System.out.println("The Make, Model and Price of the car is: m + mo + p ");
}
The return statement means that the two following statements can never be reached, and this will result in a compile error after you correct the first problem.
This is not a valid method name:
public String getMake + getModel + getPrice;
Fix that. If you still have problems, be a little more detailed. Maybe even post the error message!
Related
Instructions:
• The ParkingTicket Class: This class should simulate a parking ticket. The class’s
responsibilities are as follows:
– To report the make, model, color, and license number of the illegally parked car
– To report the amount of the fine, which is $25 for the first hour or part of an
hour that the car is illegally parked, plus $10 for every additional hour or part of
an hour that the car is illegally parked
– To report the name and badge number of the police officer issuing the ticket
• The PoliceOfficer Class: This class should simulate a police officer inspecting parked
cars. The class’s responsibilities are as follows:
– To know the police officer’s name and badge number
– To examine a ParkedCar object and a ParkingMeter object, and determine whether
the car’s time has expired
– To issue a parking ticket (generate a ParkingTicket object) if the car’s time
has expired
My problem: I don't understand how I'm suppose to call both classes at the same time. In main, it's impossible. My current code actually works but I'm not sure if it's correct. I don't understand how I'm suppose to only 'report' the objects in the ParkingTicket Class without 'knowing' them. Finally I don't understand how I'm suppose to generate a ParkingTicket object in the PoliceOfficer class without creating a field for the ParkingTicket class and adding that to the constructor. Thank you to whoever helps!
//Main:
public class chapter08_PE_08 {
public static void main(String[] args) {
ParkedCar car = new ParkedCar("HONDA", "CIVIC", "SILVER", "JPO4342", 132);
ParkingMeter meter = new ParkingMeter(60);
PoliceOfficer officer = new PoliceOfficer("Millard", "0723", car, meter);
officer.issueTicket(officer);
}
}
//Police officer class:
public class PoliceOfficer {
private String officerName;
private String officerBadge;
private ParkedCar car;
private ParkingMeter meter;
public PoliceOfficer(String officerName, String officerBadge, ParkedCar car, ParkingMeter meter) {
this.officerName = officerName;
this.officerBadge = officerBadge;
this.car = new ParkedCar(car);
this.meter = new ParkingMeter(meter);
}
public PoliceOfficer(PoliceOfficer officer) {
officerName = officer.officerName;
officerBadge = officer.officerBadge;
car = officer.car;
meter = officer.meter;
}
public void setOfficerName(String officerName) {
this.officerName = officerName;
}
public void setOfficerBadge(String officerBadge) {
this.officerBadge = officerBadge;
}
public String getOfficerName() {
return officerName;
}
public String getOfficerBadge() {
return officerBadge;
}
public ParkedCar getCar() {
return new ParkedCar(car);
}
public boolean examineCars() {
return car.getMinutesParked() > meter.getTimePurchased();
}
public double calculateFine() {
double totalTime = car.getMinutesParked() / 60;
boolean fine = examineCars();
double baseFine = 25.0;
if (fine && totalTime > 1 && totalTime < 2) {
return baseFine;
} else if (fine && totalTime > 2) {
double hourlyFine = 10.0;
return baseFine + (hourlyFine * totalTime);
} else {
return 0;
}
}
public void issueTicket(PoliceOfficer officer) {
ParkingTicket ticket = new ParkingTicket(officer);
boolean fine = examineCars();
if (fine) {
System.out.println(ticket.generateTicket());;
} else {
System.out.println("Moving on...");
}
}
}
//Parking ticket class:
public class ParkingTicket {
private PoliceOfficer officer;
public ParkingTicket(PoliceOfficer officer) {
this.officer = new PoliceOfficer(officer);
}
public String generateTicket() {
return "\nParking Ticket" +
"\n--------------" +
"\nCar information: " + officer.getCar() +
"\nOfficer name: " + officer.getOfficerName() +
"\nOfficer badge number: " + officer.getOfficerBadge() +
"\nYour fine: " + String.format("$%,.2f", officer.calculateFine());
}
}
Change public void issueTicket(PoliceOfficer officer) { to take a ParkedCar as an argument rather than a PoliceOfficer.
You already have a PoliceOfficer, so no need to pass one. The officer variable on which you are calling the issueTicket already refers to a PoliceOfficer object. What you need is tell that officer what car deserves to be ticketed.
So this:
public void issueTicket( PoliceOfficer officer ) {
…becomes:
public void issueTicket( ParkedCar parkedCar ) { …
…and this:
officer.issueTicket( officer );
…becomes:
officer.issueTicket( car );
I have an Object ArrayList and I need to use the toString() method of the Motor object, which is a parameter of the Vehicle object. My vehicle objects are in an ArrayList which is iterated through with a for-loop (I know a foreach loop would be easier, but this is part of the assignment)
Here is the code for the loop:
for (int i = 0; i < VehicleList.size(); i++) {
System.out.println();
String info = VehicleList.get(i).toString();
Motor m = VehicleList.get(i).motor;
String motorInfo = m.toString();
System.out.println(info);
System.out.println(m);
}
There is an error that says "motor cannot be resolved or is not a field".
All of the classes should allow this to work, unless of course there is a simple mistake I am missing.
Here is the Motor class:
public class Motor {
protected String name;
protected int cylinders;
protected int bhp;
protected double displacement;
public Motor(String name, int cylinders, int bhp, double displacement) {
this.name = name;
this.cylinders = cylinders;
this.bhp = bhp;
this.displacement = displacement;
}
public String toString() {
return "Motor name= " + name + ", cylinders= " + cylinders + ", bhp=
" + bhp + ", displacement= " + displacement;
}
}
Motors and Vehicles are intitialized here (In the TestVehicle class):
//Motors
Motor EcoBoost = new Motor("EcoBoost", 6, 310, 2.3);
Motor Hemi = new Motor("Hemi", 8, 707, 5.7);
Motor P90D = new Motor("P90D", 0, 762, 0.0);
//Vehicles
Vehicle v0 = new PassCar("Ford", "Mustang", 2016, 44500.0, 5, true, EcoBoost);
Vehicle v1 = new PassCar("Tesla", "Model S", 2016, 121000.0, 2, true, P90D);
Vehicle v2= new Truck("Dodge", "Ram", 2016, 46000.0, "pickup", 1500, Hemi);
PassCar and Truck are inherited classes of Vehicle with a few more attributes. I can post the PassCar or Truck class if needed but I do not think that is where the problem is arising from. I believe it is coming from the For-Loop, specifically the line Motor m = VehicleList.get(i).motor; but I am not sure of how to fix it.
Vehicle Class:
public class Vehicle {
protected String make;
protected String model;
protected int year;
protected double price;
public Vehicle(String make, String model, int year, double price) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
}
public void description() {
System.out.println("Description");
}
public String toString() {
return "make= " + make + ", model= " + model + ", year= " + year +
", price= " + price;
}
}
EDIT: There cannot be any Getters or Setters as per the assignment requirements, and it must be an ArrayList, not a regular List. When I switch to I get the error "Type mismatch: cannot convert from ArrayList to ArrayList
Here is an image of the classes:
ArrayList<Object> VehicleList = new ArrayList<>(Arrays.asList(vehicles));
VehicleList is declared to contain instances of Object, so the compiler will only let you access methods and fields it knows exist on all instances of Object.
Change it to ArrayList<Vehicle>.
First, mind the naming convention. Variables should be named in camcelCase e.g. vehicleListinstead ofVehicleList`
I have an Object ArrayList
I believe you mean declaration of vehicleList looks like ArrayList<Object> vehicleList
Then behavior is expected because compiler only knows that VehicleList.get(i) is going to return you an Object reference. It can be a Vehicle, but it can also be anything else. So it won't allow you to access the motor field, as there is simply no such field in Object.
Change your declaration to something like List<Vehicle> vehicleList
However, as mentioned in other answer, it is not a good idea to access the field directly because of various reason. A slightly less evil way is to have getter of motor. (A better way is to provide meaningful behaviors instead of providing access to internal data)
Create an interface IMotor which is used by Vehicle class and Implemented in PassCar and other implementation of vehicle.
IMotor.java
public interface IMotor {
public Motor getMotor();
}
Motor.java
public class Motor {
protected String name;
protected int cylinders;
protected int bhp;
protected double displacement;
public Motor(String name, int cylinders, int bhp, double displacement) {
this.name = name;
this.cylinders = cylinders;
this.bhp = bhp;
this.displacement = displacement;
}
public String toString() {
return "Motor name= " + name + ", cylinders= " + cylinders + ", bhp=" + bhp + ", displacement= " + displacement;
}
}
Vehicle.java
public abstract class Vehicle implements IMotor{
protected String make;
protected String model;
protected int year;
protected double price;
public Vehicle(String make, String model, int year, double price) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
}
public String toString() {
return "make= " + make + ", model= " + model + ", year= " + year +
", price= " + price;
}
}
PassCar
public class PassCar extends Vehicle{
protected Motor motor;
public PassCar(String make, String model, int year, double price, Motor motor) {
super(make, model, year, price);
this.motor = motor;
}
public Motor getMotor() {
return motor;
}
}
Test.java
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args) {
Motor EcoBoost = new Motor("EcoBoost", 6, 310, 2.3);
Vehicle v0 = new PassCar("Ford", "Mustang", 2016, 44500.0, EcoBoost);
List<Vehicle> vehicles = Arrays.asList(v0);
System.out.println(vehicles.get(0).getMotor());
}
}
Your problem is that motor is not a member of the Vehicle class, but you are trying to access it through an expression of type Vehicle - namely vehicleList.get(i). This is forbidden, because the compiler has no way of knowing that every possible kind of Vehicle has a motor. After all, what would happen if you added a Bicycle class?
To make this work, you should remove motor from the Truck and PassCar classes, and add it to the Vehicle class. That way, vehicleList.get(i).motor would actually make sense, since the Vehicle expression would be guaranteed to refer to a Vehicle with a Motor.
It would also be recommended to use a getter for the motor field - that is, have motor as a private field of the Vehicle class, and write a method getMotor() to return it. You could then write vehicleList.get(i).getMotor() to get the Motor object associated with one Vehicle in the list.
Thanks to the help of all of your comments and my Java textbook, I managed to piece it together. Here is how I got it to work:
for (int i = 0; i < vehicleList.size(); i++) {
String motorInfo = "";
String info = "";
System.out.println();
if (vehicleList.get(i) instanceof PassCar) {
info = ((PassCar)vehicleList.get(i)).toString();
**motorInfo = ((PassCar)vehicleList.get(i)).motor.toString();**
}
else if(vehicleList.get(i) instanceof Truck) {
info = ((Truck)vehicleList.get(i)).toString();
**motorInfo = ((Truck)vehicleList.get(i)).motor.toString();**
}
Basically I had to use a polymorphic call and check if it was an instance of a PassCar or Truck.
And as for the Array and ArrayList used during the Class, I edited them like this:
Vehicle [] vehicles = new Vehicle [3];
vehicles[0] = v0;
vehicles[1] = v1;
vehicles[2] = v2;
showVehicle(vehicles);
ArrayList<Vehicle> vehicleList = new ArrayList<Vehicle>(Arrays.asList(vehicles));
System.out.println();
System.out.println("Output from ArrayList in main: ");
Thank you for the help everyone!
I have a project for my java programming course.
The instructions are that we have to create a simple class and a tester class, and the class must include a Default constructor; Parameterized constructor with three parameters (make, model and price); Accessor method called getMake( ) to return the make; Accessor method called getModel( ) to return the model; Accessor method called getPrice( ) to return the price; Mutator method setMake( String newMake) to set the make; Mutator method setModel( String newModel) to set the model; and a Mutator method setPrice( double newPrice ) to set the price..
I have created my class and tester program, and my class compiles perfectly. When I try to run it, though get the error that there is no main method. Now, I followed my professor's example for the tester program and I get several errors on that. If anyone could give me the a pointer in the right direction, I would appreciate it.
My question is this: How do I implement my tester program? Do I need to create a zip file? I've tried doing so and didn't seem to help much...
The following is my code for the class:
public class Automobile
{
private String make;
private String model;
private double price;
public Automobile()
{
make = "Lexus2017";
model = "RX";
}
public Automobile(String initMake, String initModel, double initPrice)
{
make = initMake;
model = initModel;
price = initPrice;
}
public String getMake()
{
return make;
}
public String getModel()
{
return model;
}
public double getPrice()
{
return price;
}
public void setMake(String newMake)
{
make = newMake;
}
public void setModel(String newModel)
{
model = newModel;
}
Also, the following is my tester class(the one that has a lot of errors):
public class AutomobileTester
{
public static void main(String[] args)
{
Automobile make = new Automobile("Lexus 2017");
System.out.println("The car is " + make.getMake());
Automobile model = new Automobile("RX");
System.out.println("The car is " + Automobile.getModel());
Automobile price = new Automobile("43020");
System.out.println("The car is " + Automobile.getPrice());
// Use the mutator to change the make variable
Automobile.setMake("Lexus 2017");
System.out.println("The car is " + backDoor.getState());
// Use the mutator to change the model variable
Automobile.setModel("RX");
System.out.println("The car is called " + backDoor.getName());
Automobile.setPrice("43020");
System.out.println("The car is " + price.getPrice());
}
}
This is my first time working with constructors, and I'm very new to Java, so I'm sorry for any obvious errors. Thank you ahead of time for your time and help.
One of the first problems is that you do not use the proper number of parameters for your calls to the constructor, in Java (and most programming languages) you have to supply all of the required parameters to a method/function/constructor in one call. The fix for your code would be to use:
Automobile car = new Automobile("Lexus 2017", "RX", 43020.0D);
Also when you print out the cars information you first use an instance call then you use a static call, I won't go to much into the difference between the two but basically an instance call requires you to instantiate an object while a static does not. The fix for this problem would be to do:
System.out.println("The car is a " + car.getMake() + ", the brand is " + car.getModel() + ", the price is $" + car.getPrice());
As for changing the variables you should be using:
car.setMake("My New Car Make");
instead of:
Automobile.setMake("My New Car Make");
For the difference between static and instance you can look here, here, and here.
You did this correctly. You accessed the method by using the make instance variable of an Automobile class.
(side note: make is a bad name for an automobile instance, rather call it car1, or something)
Automobile make = new Automobile("Lexus 2017");
System.out.println("The car is " + make.getMake());
Now, everywhere else that you use Automobile.someMethod(), that's not right, because you need to set or get the data on one instance of the class, not the entire class.
Then, finally, you need to test the constructor with three parameters that you have in that class.
You have an error in the constructor call.
Your constructor takes three parameters (make, model and price) but when you call the method only send one. That is an error.
By default, the Java class constructor takes no parameters (in your case, this would be "new Automobile ()").
To implement the tester you have two options.
First, create the car using the constructor without parameters and then set the parameters:
Automobile auto = new Automobile();
auto.setMake("Lexus 2017");
auto.setModel("RX");
auto.setPrice(43020);
Automobile Automobile make = new Automobile ();
Another option is to use your own builder and pass parameters:
Automobile auto2 = new Automobile("Lexus 2017", "RX", 43020);
Automobile.java:
public class Automobile {
private String make;
private String model;
private double price;
public Automobile() {
}
public Automobile(String make, String model, double price) {
this.make = make;
this.model = model;
this.price = price;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
AutomobileTester.java:
public class AutomobileTester {
public static void main(String[] args) {
Automobile auto = new Automobile();
auto.setMake("Lexus 2017");
auto.setModel("RX");
auto.setPrice(43020);
System.out.println("The car1 is " + auto.getMake() + " " + auto.getModel() + " " + auto.getPrice());
Automobile auto2 = new Automobile("Lexus 2017", "RX", 43020);
System.out.println("The car2 is " + auto2.getMake() + " " + auto2.getModel() + " " + auto2.getPrice());
}
}
so I need some advice, I have been working on some code for quite a while and I can never seem to find out why my code is screwing up terribly. It seems as if one of the toString lines in my Product class is not working properly. Here is the code:
import java.util.ArrayList;
public class lab24ArrayList
{
public static void main(String[]args)
{
ShoppingCart cart = new ShoppingCart();
Product hat = new Product ("Hat", 10);
Product scarf = new Product ("Scarf", 8);
Product legos = new Product ("Legos", 19);
Product dvd = new Product ("DVD", 12);
System.out.println("Removing DVD: "+cart.remove(dvd));
cart.add(hat);
cart.add(scarf);
cart.remove(scarf);
System.out.println("Removing Scarf: " +cart.remove(scarf));
cart.add(legos);
cart.add(dvd);
cart.add(legos);
System.out.println(cart);
}
}
class ShoppingCart
{
ArrayList <Product> cart;
public ShoppingCart()
{
cart = new ArrayList<Product>();
}
public int size()
{
int k = cart.size();
return k;
}
public void add(Product p)
{
cart.add(p);
}
public Product remove(Product p)
{
if(cart.contains(p))
{
cart.remove(p);
return p;
}
else
return null;
}
}
class Product
{
private String name;
private double price;
public Product(String _name, double _price)
{
name = _name;
price = _price;
}
public String getName() {return name;}
public double getPrice() {return price;}
public String toString() {return name + ": $"+price;}
}
When I put it in the compiler, all I get is this:
Removing DVD: null
Removing Scarf: null
ShoppingCart#c2f0bd7
When I need to get this:
Removing DVD: null
Removing Scarf: Scarf: $8
Items: 6
Total: $60.00
Hat: $10
Legos: $19
DVD: $12
Legos: $19
You're missing a toString() method on your ShoppingCart, that's why you get ShoppingCart#c2f0bd7. Override toString() in the ShoppingCartclass to build a string from the items within it.
You're also removing the Scarf twice, once here cart.remove(scarf) then also in System.out.println("Removing Scarf: " +cart.remove(scarf)).
To clarify how to print out the cart, you'll want to create a toString method in ShoppingCart similar to what you've done in Product:
public static String toString() {
StringBuilder stringBuilder = new StringBuilder();
for(Product product : cart) {
stringBuilder.append(product);
}
return stringBuilder.toString();
}
That creates a StringBuilder, loops through each product in the cart and appends it to the StringBuilder. You then return that string.
Ok so I'm trying to get a better understanding of how to return a private variable from a class that I have created. I've only provided a small snippet of my main program to explain my question, so if more information is needed please let me know. My goal is to return a string from the class (working great), but also be able to return the private variables individually as needed (example used below is "flight_number").
public class Flights {
private String dest_city, dest_state, departureDate, departureTime;
private int flight_number;
public Flights(String city, String state, String dDate, String dTime, int flightNumber) {
dest_city = city;
dest_state = state;
departureDate = dDate;
departureTime = dTime;
flight_number = flightNumber;
}
public String toString() {
return "Flight number: " + flight_number + " Destination: " + dest_city + "," + dest_state + " Departing on:" + departureDate + " at" + departureTime + ".";
}
}
public class dummy {
public static void main(String[] args) {
// Uses the constructor to set values
Flights flight1 = new Flights("Houston", "Texas", "12/20/2014", "12:40 pm", 100);
System.out.println(flight1);
System.out.println(flight_number); // Error: `flight_number` cannot be resolved to a variable.
}
}
You need to add a public getter in Flights and call it from main:
public class Flights {
// all the private fields
public int getFlightNumber() {
return this.flight_number;
}
}
In Main:
public static void main(String[] args) {
Flights flight1 = new Flights("Houston", "Texas"); //...
System.out.println(flight1);
System.out.println(flight1.getFlightNumber()); // call the getter
}
You should start with an editor like eclipse and that should help you get started quickly. Getters and Setters is what you need, but start with Eclipse and you should do better.