How to call out method with parameter?( Java ) - java

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

Related

Cannot pass random enum value to function in Java

Cheers, I am pretty new to java and I and I have ran across a problem
I have three classes, all inheriting things between them. Starting I have a class A:
public class A{
private int index;
public A(int index) {
System.out.println("Creating an instance of A");
this.index = index;
}
}
then I have a sublass of A, class M which has a enum inside as:
public class M extends A{
public enum Letter {
A,B,C;
}
private Letter letter;
public M(int index, Letter aLetter) {
super(index);
System.out.println("Creating an instance of M");
this.letter = aLetter;
}
}
and finally a last class P , subclass of M:
public class P extends M {
private T t;
public enum T{
o,
a,
t
}
public P(int index, Letter aLetter, T aT) {
super(index,aLetter);
System.out.println("Creating an instance of P");
this.t = aT;
}
}
What I want to do is create e.g. 3 objects of the class P, and pass on to them RANDOMLY a value of each of these enums. I thought of creating a function in the main class which would be kind of like:
Letter getRandLetter() {
Random rand = new Rand();
int pick = rand.nextInt(M.Letter.values().length);
if (pick == 0) {
return Letter.A;
} else if (pick == 1) {
return Letter.B;
} else {
return Letter.C;
}
}
my main looks like this:
int N = 3;
M[] new_m = new M[N]
for(int i = 0; i < N; i++) {
new_m[i] = new P(i, getRandLetter(), getRandT());
}
however I get this error: Cannot make a static reference to the non-static method . What Can I do to achieve what I want?
The error is telling what to do:
Cannot make a static reference to the non-static method
Your main method is static, and the methods called from it should be static as well. So your getRandLetter() and getRandT() methods should be static.
getRandLetter() should look like this:
static Letter getRandLetter() {
Random rand = new Rand();
int pick = rand.nextInt(M.Letter.values().length);
if (pick == 0) {
return Letter.A;
} else if (pick == 1) {
return Letter.B;
} else {
return Letter.C;
}
}
And getRandT() should be static as well.

Connecting two classes

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.

Setters And Getters to different Class

My problem is that, simply I don't know what code to use to get my value from my getX method to my other classses main method.
package hangman;
public class Hangman {
private int triesLimit;
private String word;
public void setTriesLimit(int triesLimit) {
this.triesLimit = triesLimit;
}
public void setWord(String word) {
this.word = word;
}
public int getTriesLimit() {
return this.triesLimit;
}
public String getWord() {
return this.word;
}
#Override
public String toString() {
return ("Enter Secret Word " + this.getWord()
+ ".\nEnter max # of tries (Must be under 7) "
+ this.getTriesLimit());
}
}
Thats from the sub-class and I am trying to store the value of the triesLimit into the main of this classes main method
package hangman;
public class PlayHangman {
public static void main(String[] args) {
Hangman hangman = new Hangman();
Scanner scn = new Scanner(System.in);
int triesCount = 0;
int correctCount = 0;
hangman.toString();
int triesLimit = hangman.getTriesLimit();
String secretWord = hangman.getWord();
StringBuilder b = new StringBuilder(secretWord.length());
for (int i = 0; i < secretWord.length(); i++) {
b.append("*");
}
char[] secrectStrCharArr = secretWord.toCharArray();
int charCnt = secretWord.length();
for (int x = 0; triesCount < triesLimit; triesCount++) {
while (charCnt >= 0) {
System.out.println("Secrect Word :" + b.toString());
System.out.println("Guess a letter :");
char guessChar = scn.next().toCharArray()[0];
for (int i = 0; i < secrectStrCharArr.length; i++) {
if (guessChar == secrectStrCharArr[i]) {
b.setCharAt(i, guessChar);
correctCount++;
} else if (guessChar != secrectStrCharArr[i]) {
triesCount++;
System.out.println("Incorrect: " + triesCount);hangmanImage(triesCount,correctCount);
}
}
}
}
}
I tried looking it up on here but couldn't find setters and getters used in a sub/superclass
You need to create an instance of the class in the main method to access the variables and method available in that class like so
public class PlayHangman {
public static void main(String[] args) {
Hangman hangman = new Hangman();
hangman.setTriesLimit(2)
int value = hangman.getTriesLimit();
}
You can look into static keyword to access the value directly but that requires a bit more understanding of OOP's and JAVA.
This should work fine.
Hope it helps :)
EDITED
ToString method is just to convert everything in your model class to String which you have done correctly,but you have implemented incorrectly.... Change your ToString content so
#Override
public String toString() {
return ("The Secret Word you entered: " + this.getWord()
+ ".\n The max # of tries (Must be under 7): "
+ this.getTriesLimit());
}
You have initialized Scanner which does what you want, to ask the user to enter the values but again you haven't implemented it so add this to your main method
Scanner scn = new Scanner(System.in);
hangman.setTriesLimit(scn.nextInt());
hangman.setWord(scn.next());
hangman.toString()//Will work now
Trial and error is your best friend now :)
and Google some of the issues rather than waiting for an answer :)
Like rohit said, this is as simple as understand the basics of OOP, specific the encapsulation.
If you want to get a little deeper into OOP patterns, you could use the Observer pattern. This allows you to change the status of any class instance, even if they're not related by inheritance, aggregation, etc.
You can scale the solution by making List of Observer
Your observable interface
public interface IObservable {
// Set the observer
public void setObserver(IObserver iObserver);
// Notify the observer the current status
public void notifyObserver();
}
Your observer interface
public interface IObserver {
public void update(boolean status);
}
Your observer implementation
public class PlayHangman implements IObserver {
private boolean status = false;
public void printStatus() {
System.out.println("Status: " + (this.status ? "Win" : "Lose"));
}
#Override
public void update(boolean status) {
// The instance status is updated
this.status = status;
// Print the current status
this.printStatus();
}
}
Your observable implementation
public class Hangman implements IObservable{
private String goalWord = "";
private String currentWord = "";
private int triesLimit = 0;
private int tries = 0;
private IObserver iObserver;
public Hangman(String goalWord, int triesLimit) {
this.goalWord = goalWord;
this.triesLimit = triesLimit;
}
public void setCurrentWord(String currentWord) {
this.currentWord = currentWord;
this.notifyObserver();
}
public void addTry() {
this.tries++;
this.notifyObserver();
}
#Override
public void setObserver(IObserver iObserver) {
this.iObserver = iObserver;
}
#Override
public void notifyObserver() {
// True = win
this.iObserver.update(this.tries < this.triesLimit &&
this.goalWord.equals(this.currentWord));
}
}
Your Main class
public class Main{
public static void main(String[] args) {
// PlayHangman (game status)
PlayHangman playHangman = new PlayHangman();
// Hangman initializes with a goalWord and the triesLimit
Hangman hangman = new Hangman("HangmanJava", 5);
// Set the observer
hangman.setObserver(playHangman);
// During the game you just can set the current word and add a try
// You're not setting the status directly, that's the magic of the Observer pattern
hangman.setCurrentWord("Hang");
hangman.addTry();
hangman.setCurrentWord("HangmanJava");
}
}
Hope this helps and enjoy Java

How to create objects from a class with private constructor?

I have a class Game that is my main class and a second class Card.
Class Card hast its properties and constructor private, only function init is public.
Function init checks values for plausibility and if everything is fine than the constructor gets the values and creates an object.
Now I wannt in class Game to create an object from class Card.
How should I do this?
Here is my code:
Class Game:
import java.util.List;
import java.util.Vector;
public class Game {
public static void main(String[] args)
{
/*
CREATING NEW CARD OBJECT
*/
int value = 13;
Vector<Card> _card_set = new Vector<Card>();
for (int i = 2; i < 54; i++)
{
if(--value == 0)
{
value = 13;
}
Card _myCard;
_myCard.init(i,value);
}
}
}
Class Card:
public class Card {
private int index;
private int value;
private String symbol;
/*
CREATING A PLAYCARD
*/
private Card(int index,int value)
{
this.index = index;
this.value = value;
value = (int) Math.floor(index % 13);
if(this.index >= 2 && this.index <= 14)
{
this.symbol = "KARO";
}
else if (this.index >= 15 && this.index <= 27)
{
this.symbol = "HERZ";
}
else if (this.index >= 26 && this.index <= 40)
{
this.symbol = "PIK";
}
else if (this.index >= 41 && this.index <= 53)
{
this.symbol = "KREUZ";
}
System.out.println("Card object wurde erstellt: " + symbol + value);
System.out.println("------<><><><>------");
}
/*
SHOW FUNCTION
GET DETAILS ABOUT PLAYCARD
*/
public String toString()
{
return "[Card: index=" + index + ", symbol=" + symbol + ", value=" + value + "]";
}
/*
Initialize Card object
*/
public Card init(int index, int value)
{
/*
Check for plausibility
if correct constructor is called
*/
if((index > 1 || index > 54) && (value > 0 || value < 14))
{
Card myCard = new Card(index,value);
return myCard;
}
else
{
return null;
}
}
}
You should define your init method as static, implementing the static factory method that Braj talks about. This way, you create new cards like this:
Card c1 = Card.init(...);
Card c2 = Card.init(...);
...
As #Braj mentioned in comments, you can use static factory. Private constructor cannot be accessed outside of class, but it can be accessed from inside, like the following:
public class Test
{
private Test(){
}
static Test getInstance(){
return new Test();
}
}
This pattern can be used for making Builders, for example.
Note :
You can access private constructor from within the class itself as in a public static factory method.
You can access it from the enclosing class it its a nested class.
public class demo
{
private demo()
{
}
public static demo getObject()
{
return new demo();
}
public void add()
{
}
}
class Program
{
static void Main(string[] args)
{
demo d1 = demo.getObject();
d1.add();
}
}
I would say don't make the constructor private, don't make the build code under the constructor (place it in a new method, which can be private) and make a method to return the card outside the class.
Then use the card object and call the method to retrieve your card from the Card class, make sure to declare the type Card and make sure that the method returns properly.
Class<?> class = Class.forName("SomeClassName");
Constructor<?> constructor = class.getConstructors[0];
constructor.setAccessible(true);
To convert the privately declared constructor to the public one till program execution. Also, this concept is related to Reflection API.
Object o = constructor.newInstance();
if(o.equals(class)) {
System.out.println("Object for \"SomeClassName\" has been created");
}

The method is there but it does not work like it's supposed to

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

Categories

Resources