简体   繁体   中英

Error : Cannot resolve method

I was trying to create a program that had multiple characters with different attributes. I ran into an issue calling a method I (tried) to define in Class Character.

public class CharacterAttributes
{
    public static void main(String[] args) 
    {
       Character John = new Character("John", 0);
       workout(5);
    }
}
class Character
{
   private String name;
   private int Str;
   public Character(String n, int initialStr) 
   {
      name = n;
      Str = initialStr;
   }
   public void workout(int byAmt) {
      Str = Str + byAmt;
   }
}

The compiler said the "workout()" method could not be resolved.

Thanks!

There's probably a lot of errors, honestly.

The method belongs to class Character , so you should call it against the instance John :

John.workout(5);

As a side note, it is conventional to start the name of a variable with a lowercase ( john instead of John and str instead of Str ), and to give them names that reflect their type ( Str gives a hint that it's a String while it is in fact an int ).

EDIT:

Based on your comment, if you would like to call the method workout the way you're doing, you can move the method to the CharacterAttributes class, and change it so that it takes a reference to the Character instance that will be updated.

public static void main(String[] args) {
    Character John = new Character("John", 0);
    workout(John, 5);
}

public static void workout(Character character, int byAmt) {
    // use a setter to set the attribute
    character.setStr(character.getStr() + byAmt);
}

class Character {
   private String name;
   private int Str;
   public Character(String n, int initialStr) {
       name = n;
       Str = initialStr;
   }
   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public int getStr() {
       return Str;
   }
   public void setStr(int str) {
       Str = str;
   }
}

You can't just do workout(5)

you did this

Character John = new Character("John, 0);

so you do:

John.workout(5)

and sorry but your conventions are pretty bad

public int Str should be public int str

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM