whats is wrong in this basic method Java? - java

i'm newbe in this programming language (in almost too), i just wanna use a "if and else" with getter and setter methods, i'm doing a basic RPG for learning purpose.
I've a character x, and all i wanna do is; if the life of this character is lower than 0 revive this character,else just increase his life. This is my
code.
public Skill bless(Character x) {
if (0>= x.getCurrentHp()) {
x.getCurrentHp() == x.getHp() * 3/4;
}
else if (x.getCurrentHp() > 0) {
x.getCurrentHp() =+ x.getHp() * 1/2;
}
return x;
}

Well, the issue is in these lines:
x.getCurrentHp() == x.getHp() * 3/4;
x.getCurrentHp() =+ x.getHp() * 1/2;
You have to use methods like:
x.setCurrentHp(x.getHp() * 3/4);
x.setCurrentHp(x.getHp() * 1/2);
Under the hood methods setCurrentHp / getCurrentHp should be like the following:
public class Character {
private int currentHp;
// ... other methods and fields
public void setCurrentHp(int hp){ currentHp = hp; }
public int getCurrentHp(){ return hp; }
}
Because when you call x.getCurrentHp() it simply returns the value. And then you are just assigning x.getHp() * 1/2 to that value.
As a tutorial, you can refer to official examples of getter/setter methods.

Instead of
x.getCurrentHp() == x.getHp() * 3/4
Use
x.setCurrentHp(x.getHp() * 3/4)
Notice I change it to a Set method. Assuming this method has already been created.

Related

How do you put integers within a range in Java?

Though I am sure that this answer is simple, I am not sure that is asked of me for this assignment. Here is the full code that I have written (so just a return!) as well as the instructions that were given:
package code;
/**
* This class contains a variety of methods that will be used throughout the Ratings and Reviews
* project.
*/
public class Utilities{
/**
* Computes the average of two ratings
*
* #param rating0 An integer rating in the range of 1-5 inclusive
* #param rating1 An integer rating in the range of 1-5 inclusive
* #return the average of rating0 and rating1 as a double
*/
public double averageRating(int rating0, int rating1){
return ((rating0 + rating1) / 2); // Don't forget to replace this return statement with your own
}
Sorry for bad structure upon pasting it. I think my return is suitable for what is being done, provided that the rating could be just anything. I know that it can only be between 1-5, though, so how would one go about specifying that?
How about throwing an InvalidArgumentException if the range is violated?
e.g.
public double averageRating(int rating0, int rating1){
if (rating0 < 1 || rating0 > 5 || rating1 < 1 || rating1 > 5) {
throw new InvalidArgumentException("Rating out of range");
}
return ((rating0 + rating1) / 2.0); // Don't forget to replace this return statement with your own
}

Creating constructors for a temperature converter

Write a Temperature class that represents temperatures in degrees in both Celsius and Fahrenheit, using a floating-point number for the temperature and character for the scale: either ā€˜Cā€˜ for Celsius or ā€˜Fā€˜ for Fahrenheit. The class should have
Four constructors:
one for the number of degrees,
one for the scale,
one for both the degrees and the scale, and
a default constructor.
For each of these constructors, assume zero degrees if no value is specified and Celsius if no scale is given."
Hey there I am an amateur java programmer... I have been asked to do the above statement and I am not all that familiar with constructors but I'm open to any knowledge :) obviously I'm not asking for someone to give me an answer to my question but maybe someone can give me some advice on how I get started... here's what I have done so far:
public class TemperatureApparatus {
public class temperature{
private float c;
private float F;
public temperature(){
}
public temperature(){
}
public temperature(){
}
public temperature(){
}
}
public static void main(String[] args) {
}
}
Four constructors: one for the number of degrees, one for the scale,
one for both the degrees and the scale, and a default constructor.
These are your constructor arguments. Arguments are passed into constructors and methods via parameters which are listed within the parentheses of the method.
You've got the format of a constructor correct. It's essentially a method that has the same name of the class and no return type. Now you need to add arguments.
The default constructor has no arguments:
public Temperature() { //Class names should be capitalized!
//Default constructors often do nothing, but you can set default values here if you want
}
Here's a signature for a constructor taking the degrees only:
public Temperature(float degrees) {
//Assign the "degrees" argument to an instance variable here
//You might consider assigning a value to a "scale" variable by default as well
}
This assignment probably wants you to fill in that constructor's body, so assign the given value to a float in the class. Now make constructors for the other desired arguments. Since the assignment wants 'F' or 'C' for the scale, you can safely use char as the argument for that data.
Once you've completed the assignment, you might consider challenging yourself with this: Given that a user could now have a Temperature object with a float degree and a char scale, how might you implement a getTemperature() method?
Oh, and there's no reason for you to nest classes like you are. Put Temperature in a separate class from your class that runs main if you need to make a runnable answer.
Here you go
public class Temperature {
private float temp;
char scale;
//first constructor
/*
*Notice how in this first constructor, I put scale
*as 'C' since there was no char value being passed
*as a parameter (no char scale inside the brackets)
*Now i did get a float temp passed a a parameter so
*I set whatever that temp is to the temp of this class
*also known as this.temp (this refers to THIS class
*/
public Temperature(float temp) {
this.temp = temp;
scale = 'C';
//other way
//this(temp, 'C');
}
//second constructor
/*
*Now this constructor is the exact same case at the
*first one, except this one has the char scale passed.
*Since no temp is passed, I set it to 0 as no value is specified
*/
public Temperature(char scale) {
this.scale = scale;
temp = 0;
//other way
//this(0, scale);
}
//third constructor
/*
*This third one is having both temp and scale being specified
*which means you don't need to put any initial value (0 and Celcius)
*Just set these objects to whatever is being passed by through the
*parameters
*/
public Temperature(float temp, char scale) {
this.temp = temp;
this.scale = scale;
}
//fourth constructor
/*
*This last one has no parameters through so
*you can just set both the scale and temp to
*0 and 'C' respectively.
*/
public Temperature() {
temp = 0;
scale = 'C';
//other way
//this(0, 'C');
}
}

Programming Assignments-Recursion

Still learning and I cant seem to wrap my head on what seemed like an easy task.
The computeMethods method's is where im totaly stumped, however the reverse method i just keep getting back the same integer without it being reversed.
/****************************
* For Method Computemethods1 i must compute series
* b(x)=1/3+2/5+3/7..... +x/2x+1
* For method ComputeMethod2
* 1/2+2/3+......... x/(x+1)
*******************************/
public static int computeMethod1(int x){
if (x==0)
return 0;
if (x==1)
return 1;
return computeMethod1(x-1/3/(x-1))+computeMethod1(x-2/3/(x-2));
}
public static int computeMethod2(int x){
if (x==0)
return 0;
return computeMethod2((x-1)/(x-1)+1)+computeMethod2((x-2)/(x-2)+1);
}
/********************
* For method reverseMethod i must reverse a user given int
**********************/
public static int reverseMethod(int x){
int reversedNum=0;
if (x!=0)
return x;
reversedNum=reversedNum *10 +x%10;
return reversedNum+reverseMethod(x/10);
}
/******************
* For method sumDigits i must use recursion
* to sum up each individual number within the int
********************/
public static long sumDigits(long n){
if( n==0)
return 0;
if (n==1)
return 1;
else
return n+sumDigits(n-1);
}
}
For reverse method, you are using: if (x!=0) return x;
May be you need to use: if (x==0) return x. So the logic is, if the given argument is 0, then return 0, else return reversed number.
P.S.: As somebody mentioned in comentaries, please take care of types, so for the division you are better using float or double, and take care of operations precedence for correct result, so (x+1)/2 will be different from x+1/2.
For each of your methods, follow through your code for small x.
For example, computeMethod1 should return:
1/3 for x == 1, whereas at the moment it simply returns 1 (Note, the return type will need to be something other than int.).
1/3 + 2/5 for x == 2.
1/3 + 2/5 + 3/7 for x == 3.
For each x, notice how we can use the previous result i.e. computeMethod1(x - 1).
When you come across code that doesn't seem to do what you expect, make your code simpler and simpler until you can narrow down where the problem is, then hopefully it will be obvious what the problem is, or online documentation can tell you.

Recursive method with wrong parameter

This was my answer to a question in which I was supposed to convert an iterative method to a recursive method. The teacher told me I cant use a-=1 as a parameter... So they gave me 0 points..
When I run this it works as it supposed to be..
Could someone tell me why its wrong?
public int do(int a){
if(a==0){
return 1 ;
}else{
return a * do(a-=1);
}
}
The problem with your code is that you're reading the value of a and reassigning it with a -= 1 in the same expression, but the order of these operations is not specified. The statement:
return a * do(a -= 1);
could be implemented as:
temp = a;
a -= 1;
return temp * do(a);
which will do what you were probably expecting, or:
a -= 1;
return a * do(a);
which will multiply by the decremented value of a rather than its original value.
The correct way to write your function is:
public int do(int a){
if(a==0){
return 1 ;
}else{
return a * do(a-1);
}
}
Just pass the result of the subtraction as an argument, don't reassign the variable at the same time.
I assume that this is in java?
I see two big problems with this snippet.
do is a reserved keyword. It may cause compilation errors, so you should name your method something else.
Executing -= in a parameter call seems quite ambiguous. Will the negation operator run before or after the multiplication by a? The more clear operator to use would be simply the - operator, and it would complete with the same result.
That said, something like this might have been what the teacher was looking for:
public int calculateSomething(int a) {
if (a == 0) {
return 1;
} else {
return a * calculateSomething(a - 1);
}
}

Return the same random int 3 times and repeat

I'm working on an assignment and it's going fairly well, but I am confused about one thing so far. The point is to learn about inheritance and reading through existing code. Without adding another method, I need to make the getMove() method return the same random number three times in a row, and then pick a new random number and have it return the new number three times. etc. etc.
There are several other classes, including a class that maintains a count separate from the one I established here. If it would be useful to see any of those classes let me know and I'll post them, but I think they are fairly irrelevant to the question.
Edit: Clarification
I need to make the getMove() method return one int per call. The 1st 3 calls should return the same randomInt. After that a new randomInt should be chosen, and that should be returned for the next three calls. This should repeat as long as it's called.
The final solution:
public class Crab extends SeaCreature {
private static final char CRAB = 'C';
private int direction = rand.nextInt(4);
private int count;
/**
* Construct a SeaCreature object with the given character representation
* #param c the character for this SeaCreature
*/
public Crab(){
super(CRAB);
}
/** Answers back the next move for this SeaCreature.
* #return 0, 1, 2, or 3
*/
public int getMove() {
if (count < 3) {
count ++;
return direction;
}
count = 1;
direction = rand.nextInt(4);
return direction;
}
}
Not that it's a "problem", but your fields should be instance fields (ie not static).
However, to isolate the problem from your classes, here's code that works. Note that you can get the same move on subsequent calls to rand().
private static int direction = rand();
private static int count;
public static int getMove()
{
if (count < 3)
{
count++;
return direction;
}
count = 0;
direction = rand();
return direction;
}
private static int rand()
{
return (int) (Math.random() * 4); // 0, 1, 2 or 3
}
I can see the problem I think.
Hint - you need to think through carefully which state belongs to all Crabs, and which state is specific to an individual Crab. You've currently got that wrong, and all Crabs are sharing some state that they shouldn't. Assuming that there are lots of live Crab instances, this will result in getMove() not behaving as you want it to.

Categories