• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

java beginner, need help with code

 
Greenhorn
Posts: 14
Eclipse IDE Fedora Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a very simple combat style of code here. I am a beginner in java so its very simple. I'm on chapter 4 on head first java so the code is based on the knowledge I know. Can you help me out here?







The code is simple but there is several things I couldn't find out how to do:
1. I made two objects, a monster object and a knight object, I intended to make them try to attack each other but didn't know how to. When you run the program it seems that the knight is attacking the monster but really its taking the knights health and writing in the command line that it is taking the monsters health which it isn't. How do I make objects interact with each other?

2. I learned that this isn't the way to make code, you have to have PRIVATE instance variables but when I made them private the combat system class couldn't read them and I didn't know how to put the getter and setter methods here. Can you show me how to put the getter and setter methods.

3. I intended to make the damage variable generate a random number but when it generates a random number it sticks with the same number. I was trying to make it generate a random number every time it hits for damage. Can you show me how to do that?
 
Ranch Hand
Posts: 68
3
Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I tried not to go bananas and rewrite everything. Though...I pretty much did. Let's take it class by class, shall we?



Instead of assigning values to the fields of both types through a setter I created constructors for each type that accept an int value as a parameter. The classes Knight and Monster each have a constructor that assigns this int to their health field.
The attackMonster() method has been changed to accept a parameter of type Monster. By passing an object of type Monster through we are allowing the Knight class, which contains the attackMonster() method, to access fields and methods of class Monster.



The field health has now been marked as private. This is commonly known as encapsulation and helps to maintain safe code. It is not a huge deal for our purposes here but helps to develop a good OO mindset for future projects.
The argument constructor has been written to accept an int and assign it to the health field.
There is now a getter method for the health field and also a setter method for the health field as well.



Now here is the majority of the code. All placed into the Knight class...

Again, I have encapsulated the health field by marking it as private.
An argument constructor has been provided, just like the monster class.
The attackMonster() method has been changed to accept a Monster object as an argument.
The random() method has been placed INSIDE of the while loop. This way every time we iterate inside of the while loop we assign a new random value to damage.
Slight modifications have been made to both if blocks for formatting and shorthand.

The if-else blocks make it so that you won't get a negative value printed when the monster is brought below 0 health.


After working on rewriting some of this code I really want to give you clear answers to your three questions. They are all presented in the code but let me use just plain English to help you out, Jonny.

To make objects interact with each other you can take a look at how I introduced the Monster to the Knight. My whole goal before I started writing any code was that I knew I needed to be able to access the Monster's health field from the attackMonster() method, which is inside of the Knight Class. To accomplish this I decided to stay mostly
true to your original code and do it in the main method. When I invoke the attackMonster method I pass the Monster that will be getting attacked through the method. Once this happens I have access to the Monster class through the Knight class, ultimately allowing me to set the Monster's health field while it's being attacked.

The Private instance variables are very straight forward. As a rule of thumb, mark your instance variables (fields) private. You'll need setters and getters to access them and you can see very clearly how I implemented those into the Monster class.

To create a new Random Number each time all you had to do was move that statement inside of the while loop. So every time we iterate, we get a new value.

I do hope this was a help to you, Jonny. If you really want to benefit from my help here I have a few challenges for you to try.

1. Implement Getters and Setters into the Knight class.
2. Take a look at the attackMonster() method code and see if you can make it better, much better. There is a way.
3. Implement a way so the monster can attack back to the Knight. It wouldn't be fair if just the Monster could take damage, now would it?

If you accept my challenges, give them a shot and post back here with your results. Let's see what you've got, Jonny boy!
 
jonny Alva
Greenhorn
Posts: 14
Eclipse IDE Fedora Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hey man thank you so much the explanation came out crystal, and that quote you sent me is really great and uplifting. I'll do the challenge that you said, ill post it here when i'm done. Seriously man, thank you
 
Skye Antinozzi
Ranch Hand
Posts: 68
3
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm glad to hear it! Also, it was not a quote, ^_^ those were my own words. Looking forward to seeing your improvements! Best of luck!
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Good grief! What a load of long comments. It took me a long time to break them so we can actually read the post. Please use /* comments */ which span several lines. I broke some code lines too, and you can see how to do it. I think I added a hash # by mistake. Sorry.

There are some things I suggest you improve. The Monster constructor and the setHealth method would allow any value which is a valid int. Do you really have monsters with health -1234567890?
You are mixing System.out.print and println. Use as few print calls as possible. If you can amalgamate two calls into one, you can save several milliseconds. It might not seem a lot here, but it will make a lot of difference if you have millions of calls. You can use the + operator on Strings as often as you like, all inside the same statement, and execution will be fast.
You have repeated code in lines 40 and 50, and 59 and 72. That should be refactored.
Only write \n or \r if somebody has told you they want LF and CR characters. Use println or better printf with the %n tag. Or you can get the line end from the System class. I would use printf myself.
Go through all the possible values for the random damage and work out what will be printed. You can shorten the procedure by starting at 44 and ending at 46 Is that what you wanted?
Is Math.random() the best way to get a random int? I don't think it is. What do you think that largest value possible from your random call will be, and what the smallest is?
You are going on about injuring the monster (surely a Knight would only kill a Dragon, and where is the PrettyMaiden class ?), but you are not. You are injuring an int. Then you pass that back to the monster. Why don't you attack the monster object directly?

I presume the idea of the game is that the knight always wins? Otherwise you would have Monster#recover methods and the Knight could suffer damage, too.
 
Skye Antinozzi
Ranch Hand
Posts: 68
3
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You heard the man, Jonny. Make it better. Lol.
 
jonny Alva
Greenhorn
Posts: 14
Eclipse IDE Fedora Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Lol i know i heard.

You are mixing System.out.print and println. Use as few print calls as possible. If you can amalgamate two calls into one, you can save several milliseconds.



You said to use as few as possible, did you mean use System.out.println command as least as possible or did you mean use System.out.print as least as possible?

You have repeated code in lines 40 and 50, and 59 and 72. That should be refactored.



Is it bad if i use a lot of the same code several times in java or is that like unprofessional?

Why don't you attack the monster object directly?



How would i do that whould i just put the object as a parameter or not like that?
 
jonny Alva
Greenhorn
Posts: 14
Eclipse IDE Fedora Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

You are going on about injuring the monster (surely a Knight would only kill a Dragon, and where is the PrettyMaiden class ?)



Actually, you just gave me a good idea, i'm going to see if i can make other characters here and see if i can have them do something here.

Oh and is it also possible to make an object pause for a min? like lets say the knight attacks and then it waits until it receives the attack of the monster?
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Abstraction is a very tricky thing to master but it's one thing you really need to think about when you program. When you first start out, you tend to get caught up in all the details, such as with numbers to indicate health and the like but as you gain experience, you'll realize that the point of object orientation is to HIDE these kinds of details and make BEHAVIORS and INTERACTIONS the important things to focus on. Here's what high-level code that's focused on behaviors and interactions might look like:


This is just a start but notice how I focus on behaviors and interactions of objects instead of details like health numbers and calculations. To me, that's what OOP is about. I'll leave it as an exercise to you to figure out how to organize the code for these behaviors and interactions within the appropriate classes. There are some hints in the comments in the above listing.
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

jonny Alva wrote: . . .
You said to use as few as possible, did you mean use System.out.println command as least as possible or did you mean use System.out.print as least as possible?
. . .

I meant, if you have several print calls, join them all together. NotbutThe "" + is to ensure everything is turned into Strings and may be unnecessary in many cases.



Is it bad if i use a lot of the same code several times in java or is that like unprofessional?
. . .

It is always bad to have repeated code. What happens if you need to maintain it and change that code? What happens if you have 99 bits of repeated code and there is an error and you only correct it 98 times?



How would i do that whould i just put the object as a parameter or not like that?

Why not give the Monster a sufferAttack() method. That would be giving the monster a behaviour which there can be an interaction with.
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

jonny Alva wrote:Actually, you just gave me a good idea, i'm going to see if i can make other characters here and see if i can have them do something here.


My advice: Don't. At least not until you've got what you're writing now working. Every time.

KISS applies to programming, just as it does pretty much everywhere else - maybe even more so. So KIS: A Knight and a Monster. Get them fighting. And don't write anything else until you've had them fight LOTS of battles successfuly.

Oh and is it also possible to make an object pause for a min? like lets say the knight attacks and then it waits until it receives the attack of the monster?


Sure. But first you have to define what a "pause" is. And be specific.

HIH

Winston
 
If you settle for what they are giving you, you deserve what you get. Fight for this tiny ad!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic