I'm stuck on this one exercise where I should create a second class called Car, that is linked to Vehicle. This is how it should look:
The vehicle class along with the testprogram works great, but now I want to connect the class Car to the vehicle, and then create a testclass for car. This is my vehicle class:
public class Vehicle {
int speed;
// Constructor
public Vehicle() {
this.speed = 0;
}
public class Car extends Vehicle {
String regnr;
public Car(String regnr) {
this.regnr = regnr;
}
public String getRegNbr() {
return this.regnr;
}
}
public void increaseSpeed(int differenceInc) {
int currentSpeed = this.speed;
// Kör loopen så länge den nuvarande hastigheten inte är lika med den önskade
while (this.speed != (currentSpeed + differenceInc)) {
this.speed += 1;
System.out.println("The current speed is increasing to: " + this.speed);
}
}
public void decreaseSpeed(int differenceDec) {
int currentSpeed = this.speed;
while (this.speed != (currentSpeed - differenceDec)) {
this.speed -= 1;
System.out.println("The current speed is decreasing to: " + this.speed);
}
}
public void brake() {
int currentSpeed = this.speed;
while (this.speed != 0) {
this.speed /= 2;
System.out.println("The current speed is decreasing to: " + this.speed);
}
}
public int getSpeed() {
return this.speed;
}
public void testVehicle() {
Scanner myScanner = new Scanner(System.in);
while (this.speed != 0) {
System.out.println("You're driving at: " + " " + this.speed + "KM/H" + "\n\nDo you want to:"
+ "\n(1) Slow down to " + "lower speed??" + "\n(2) Maintain current speed?"
+ "\n(3) Hit the brakes?" + "\n(4) Accelerate even more?");
int choice = myScanner.nextInt();
if (choice == 1) {
System.out.print("By how much would you like to decrease your speed? ");
Scanner in = new Scanner(System.in);
int dec = in.nextInt();
this.decreaseSpeed(dec);
} else if (choice == 2) {
System.out.println("Maintaining current speed");
} else if (choice == 3) {
System.out.println("Breaking!");
this.brake();
}
else if (choice == 4) {
System.out.print("By how much would you like to increase your speed? (km/h)");
Scanner in = new Scanner(System.in);
int inc = in.nextInt();
this.increaseSpeed(inc);
}
else {
System.err.println("Incorrect value entererd.");
System.exit(0);
}
}
if (this.getSpeed() == 0)
{
System.out.println("Bilen står still");
}
}
}
As you can see, the testVehicle() class along with a small separate test-program called VehicleTest runs the Vehicle class I created. I've added the Car-class to the program, and it extends vehicle as it should. The only question I have is how do I implement it into the test class?
My current separate test-program looks like this:
public class VehicleTest {
/**
* #param args
*/
public static void main(String[] args) {
Vehicle bmw = new Vehicle();
Scanner scan = new Scanner(System.in);
System.out.println("How fast do you want to drive?");
int fast = scan.nextInt();
bmw.increaseSpeed(fast);
bmw.testVehicle();
}
}
You should extend Car from Vehicle. Try this:
public class Car1 extends Vehicle {
...
}
Thus you may use Car like a Vehicle.
Some info to read https://books.trinket.io/thinkjava2/chapter14.html
Derive your Car1 class from Vehicle class
public class Car1 extends Vehicle{
String regnr;
public Car1(String regnr) {
super();//pass data to parent constructor if needed
this.regnr = regnr;
}
public String getRegNbr() {
return regnr;
}
}
Now you will be able to call public methods from Vehicle class.
Car1 car = new Car1("DHM1234");
car.increaseSpeed(5); // The current speed is increasing to: 5
if you want to change behavior of any public/protected methods of your vehicle (parent) class for your car class, override that method
i.e
#Override
public void brake() {
int currentSpeed = 0;
System.out.println("Hard break");
}
now if you call brake() from car object
car.brake(); // Hard break will be printed
Give Java Inheritance a read to learn more.
Related
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.
I am making a PVP RPG game and the display box comes out with "null" instead of the variable I have already declared.
I have declared the variable as the user's next input and stored that information in the variable. Then when I try to display the variable, it only shows "null",
System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();
I already declared playerOne as a new character(different class)
System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {
This is the problem I'm coming up with. It is in the same main method and the variables are declared in the main method, and yes I imported scanner and declared the variable userInput
I expected it to be what the user typed in, but it came up with null. As I've said previous, it's in the same main method and nothing should go wrong, but it comes up with "null"
import java.util.Random;
import java.util.Scanner;
public class Arena {
Random generator = new Random();
public static void main(String[] args) {
Character playerOne = new Character(10,10,0);
Character playerTwo = new Character(10,10,0);
boolean P1hasClass = false;
boolean P2hasClass = false;
int p1Swordgo = 0;
int p2Alchgo = 0;
int p2Archgo = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerOne.name +".");
delay(1000);
System.out.println("What is your name, Player Two?");
playerTwo.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerTwo.name +".");
delay(1500);
countdown();
System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {
if (p2Archgo == 1 || p2Alchgo == 1) {
if (playerOne.move == 1){
System.out.println("What do you want to do?" +'\n' +"1 = Move into range of " +playerTwo.name +'\n' +"2 = Heal" +'\n' +"3 = Forfeit");
int P1Choice = userInput.nextInt();
if (P1Choice == 1) {
playerOne.move --;
System.out.println(playerOne.move);
}
}
}
}
}
public static void delay ( int time){
try {
Thread.sleep(time);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public static void countdown() {
delay(500);
System.out.println("Get ready to fight in 5,");
delay(1000);
System.out.println("4");
delay(1000);
System.out.println("3");
delay(1000);
System.out.println("2");
delay(1000);
System.out.println("1");
delay(1000);
System.out.println("Fight!");
delay(750);
}
}
And then in a class called Character
public class Character {
public int strength;
public double health;
public int move;
public String name;
public Character(double health, int strength, int move) {
this.health = health;
this.strength = strength;
this.name = name;
this.move = move;
}
}
And in a class called SwordFighter
public class SwordFighter extends Character {
public SwordFighter() {
super(60,15, 1);
}
}
And in a class called Archer
public class Archer extends Character{
public Archer() {
super(45,20, 0);
}
}
And finally, in a class called Alchemist
public class Alchemist extends Character {
public Alchemist() {
super(50,15, 0);
}
}
Thank you for your patience, by the way
Once the two players have chosen their name and you have set it using playerOne.name = userInput.nextLine();, you assign a different object, with a null name, to playerOne:
playerOne = new SwordFighter();
So, after this line has been executed, playerOne.name is null.
I'm working on a task given off of a textbook . I can't call out the "poisonAttack" method from the same class. Would appreciate if anyone can give me feedback.
public class PoisonMatango extends Matango {
PoisonMatango pm = new PoisonMatango ('A');
public PoisonMatango ( char suffix) {
super(suffix);
}
// The method I am trying call.
public void poisonAttack(Hero h) {
super.attack(h);
int poisonCount = 5;
if ( poisonCount >=0 ) {
System.out.println("The enemy had spread poisonous pollons");
int pollenDamage = h.hp / 5;
h.hp-= pollenDamage;
System.out.println("Hero has received " + pollenDamage + "damage from " );
poisonCount --;
}else
{
System.out.println("No additional attack were made since poisonCount= 0");
}}
}
You have to use Class object 'pm' created to call method and pass required parameter as per method definition. Your code is having Object type param of class Hero
pm.poisonAttack(hr);
Below is solution for above code:-
// Class Object used as param in solution
public class Hero {
int hp = 100;
}
// Super Class
public class Matango {
Hero a;
public Matango(Hero suffix) {
this.a =suffix;
}
// Super Class Method
public void attack(Hero h){
System.out.println("\n\nHero hp var value::"+h.hp);
}
}
// PoisonMatango
public class PoisonMatango extends Matango {
public PoisonMatango ( Hero suffix) {
super(suffix);
}
// The method I am trying call.
public void poisonAttack(Hero h) {
super.attack(h);
int poisonCount = 5;
if ( poisonCount >=0 ) {
System.out.println("The enemy had spread poisonous pollons\n");
int pollenDamage = h.hp / 5;
h.hp-= pollenDamage;
System.out.println("Hero has received " + pollenDamage + "damage from \n" );
poisonCount --;
}else
{
System.out.println("No additional attack were made since poisonCount= 0 \n");
}}
public static void main(String args[])
{
// Create Object of Param class, this example passes object but we can pass simple data type as per method definition.
Hero hr = new Hero();
PoisonMatango pm = new PoisonMatango (hr);
pm.poisonAttack(hr);
}
}
I am in an intro to java class and I am having trouble with a car class that was assigned. Here are the instructions:
Write a class named Car that has the following fields (attributes):
yearModel (an int which hold's the car's year model)
make (a String which holds the make of the car)
speed (an int which holds the car's current speed)
The Car class should have the following constructor and other methods:
Constructor - Accepts the car's year model and make as arguments.
Accessors (getters) for the object's yearModel, make, and speed fields
Methods:
accelerate - each time it is called, it should add 5 to the speed field
brake - each time it is called, it should subtract 5 to the speed field
Write a Driver class, the DrivingSimulation class, which does the following:
Prompt the user for the yearModel, make, and speed values of a car.
Create a Car object
Call the accelerate method 5 times - after each call, use the accessor method to display the current speed of the car
Call the brake method 5 times - after each call, use the accessor method to display the current speed of the car
I got most of it done but it is not receiving the speed input that I am putting, and is instead starting from default, 0. Here is my car class
package drivingsimulation;
/**
*
* #author Carlos
*/
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int yearModel, String make) {
this.yearModel = yearModel;
this.make = make;
}
public int getYearModel() {
return yearModel;
}
public String getMake() {
return make;
}
public int getSpeed() {
System.out.println("You are going " + speed + " mph");
return speed;
}
public void accelerate() {
speed += 5;
}
public void brake () {
speed-=5;
}
}
And here is my driver class:
/*
package drivingsimulation;
import java.util.Scanner;
/**
*
* #author Carlos
*/
public class DrivingSimulation {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int yearModel=0;
int speed=0;
String make=null;
Scanner keyboard = new Scanner (System.in);
Car myCar = new Car(yearModel, make);
System.out.println("What is the year of your car? ");
yearModel = keyboard.nextInt();
System.out.println("What is the make of your car? ");
make = keyboard.next();
System.out.println("How fast is your car going? ");
speed = keyboard.nextInt();
for(int i=0; i<5; i++){
myCar.accelerate();
}
}
}
Well you have a accessor for the speed class member but not setter for when you get the value from the user input in your driver class.
A method in your Car class like this:
public void setSpeed(int speed)
{
this.speed = speed;
}
Will the set value for the car instance was user input is given.
You can call it after the user input for speed like this..
myCar.setSpeed(speed);
How do you know it's not getting the speed information -- you never call getSpeed() on it.
Suggestions:
Call getSpeed() if you want to see what the speed is.
Get all println's out of the Car class. They should be in your main method only currently.
Give the class a setter method for speed -- public void setSpeed(int speed), and call the method.
For example, getSpeed() should be just
public int getSpeed() {
return speed;
}
That's it and nothing more. But you'd call it like:
System.out.println("Car's speed: " + myCar.getSpeed());
You also don't have a public void setSpeed(int speed) method, and you need one, and should call it after getting the information from the user.
Add a setSpeed() setter in your Car class and call it in your DrivingSimulation class like below (also move print statement to DrivingSimulation so your Car remains modularized).
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int yearModel, String make) {
this.yearModel = yearModel;
this.make = make;
}
public int getYearModel() {
return yearModel;
}
public String getMake() {
return make;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void accelerate() {
speed += 5;
}
public void brake () {
speed -= 5;
}
}
and...
import java.util.Scanner;
public class DrivingSimulation {
public static void main(String[] args) {
int yearModel = 0;
String make = null;
int speed;
Scanner keyboard = new Scanner(System.in);
Car car = new Car(yearModel, make);
System.out.println("What is the year of the car?");
yearModel = keyboard.nextInt();
System.out.println("What is the make of the car?");
keyboard.nextLine(); // fixes bug - receives the Enter key without skipping make = keyboard.nextLine()
make = keyboard.nextLine();
System.out.println("What speed is the initial speed of the car?");
speed = keyboard.nextInt();
car.setSpeed(speed);
for (int i = 0; i < 5; i ++) {
car.accelerate();
System.out.println("Your " + yearModel + " " + make +
" is traveling at " + car.getSpeed() + " MPH.");
}
}
}
I have the following code -in Java btw- and it compiles fine but when I input invalid parameters it doesn't recognize them as errors and accepts them as if they met the conditions.The method that concerns me is SetMPG(int average) . It's my first time here so I apologize if my question is vague I would fill in more information if necessary.
public class Vehicle {
// instance variables - replace the example below with your own
private int tireCount;
private int mPG;
/**
* Constructor for objects of class Vehicle
*/
public Vehicle(int tCount, int mP) {
// initialise instance variables
tireCount = tCount;
mPG = mP;
}
public void setTire(int tire) {
if (tire >= 0) {
tireCount = tire;
} else/*if( tire < 0)*/ {
throw new IllegalArgumentException("Values must be positive");
}
}
public void setMPG(int average) {
if (average > 0) {
mPG = average;
} else if (average < 0) {
throw new IllegalArgumentException("Values must be positive");
}
}
public int getTire() {
return tireCount;
}
public int getMPG() {
return mPG;
}
public String toString() {
return String.format("There are " + tireCount + " tires and an average of " + mPG + "mpg");
}
public class VehicleTest
{
// instance variables - replace the example below with your own
public static void main(String []args)
{
Vehicle bike = new Vehicle( 2,-23); // first parameter is for tires , second is for MPG
System.out.println(bike);
}
}
Based on your code and what you're saying, It is most likely that you are setting your parameters via the constructor. Change your constructor to be of the form:
public Vehicle(int tCount , int mP)
{
// initialise instance variables
setTire(tCount);
setMPG(mP);
}
Also not sure whether 0 is a valid value for mpg???
public void setMPG(int average)
{
if( average > 0) //should it be >= 0???
{
mPG=average;
}
else if(average < 0) // should it be <=0 ????
{
throw new IllegalArgumentException("Values must be positive");
}
}