From my understanding this is what I am attempting to do,
I am creating an interface to outline what a character is,
I am creating a class to define each method that a Character will use.
In that same class I create a new object of that character as many times as I like.
So if I want to make 10 characters I just do that all from the same class?
Currently I am attempting to create one character by giving it attributes.
Then I want to System.out.prinln but when I compile I get
javac Hero.java
Hero.java:3: error: interface expected here
public class Hero implements Character {
^
1 error
I changed Character to Player and this is what I get,
javac Hero.java Hero.java:3: error: cannot find symbol public class Hero implements Player { ^ symbol: class Player 1 error
2 files Character Interface and Hero Class
public interface Character {
// define methods that must be defined across all character types
int getLevel();
String getPrimaryAttribute();
String getAttackType();
String getAbility1();
String getAbility2();
String getAbility3();
String getAbility4();
double getStrength();
double getStrengthMultiplier();
double getAgility();
double getAgilityMultiplier();
double getIntelligence();
double getIntelligenceMultiplier();
int getHealth();
int getMana();
int getDamageMin();
int getDamageMax();
int getRange();
double getArmor();
int getMovement();
}
public class Hero implements Character {
private int level;
private String primaryAttribute;
private String attackType;
private String ability1;
private String ability2;
private String ability3;
private String ability4;
private double strength;
private double strengthMultiplier;
private double agility;
private double agilityMultiplier;
private double intelligence;
private double intelligenceMultiplier;
private int health;
private int mana;
private int damageMin;
private int damageMax;
private int range;
private double armor;
private int movement;
//default constructor
public Hero(
int level,
String primaryAttribute,
String attackType,
String ability1,
String ability2,
String ability3,
String ability4,
double strength,
double strengthMultiplier,
double agility,
double agilityMultiplier,
double intelligence,
double intelligenceMultiplier,
int health,
int mana,
int damageMin,
int damageMax,
int range,
double armor,
int movement
) {
} // End Constructor
public static void main (String[] args) {
DrowRanger();
}
private static Object DrowRanger() {
Hero DrowRanger = new Hero(
0,
"Agility",
"Ranged",
"Frost Arrows",
"Gust",
"Precision Aura",
"Marksmanship",
17,
1.9,
26,
1.9,
15,
1.4,
473,
195,
44,
55,
625,
0.64,
300);
System.out.println(DrowRanger);
return DrowRanger();
}
// getters and setters - required to implement ALL from interface
public int getLevel() {
return this.level;
}
public String getPrimaryAttribute() {
return this.primaryAttribute;
}
public String getAttackType() {
return this.attackType;
}
public String getAbility1() {
return this.ability1;
}
public String getAbility2() {
return this.ability2;
}
public String getAbility3() {
return this.ability3;
}
public String getAbility4() {
return this.ability4;
}
public double getStrength() {
return this.strength;
}
public double getStrengthMultiplier() {
return this.strengthMultiplier;
}
public double getAgility() {
return this.agility;
}
public double getAgilityMultiplier() {
return this.agilityMultiplier;
}
public double getIntelligence() {
return this.intelligence;
}
public double getIntelligenceMultiplier() {
return this.intelligenceMultiplier;
}
public int getHealth() {
return this.health;
}
public int getMana() {
return this.mana;
}
public int getDamageMin() {
return this.damageMin;
}
public int getDamageMax() {
return this.damageMax;
}
public int getRange() {
return this.range;
}
public double getArmor() {
return this.armor;
}
public int getMovement() {
return this.movement;
}
// This is where the setters are.
public void setLevel(int level) {
this.level = level;
}
public void setPrimaryAttribute(String primaryAttribute) {
this.primaryAttribute = primaryAttribute;
}
public void setAttackType(String attackType) {
this.attackType = attackType;
}
public void setAbility1(String ability1) {
this.ability1 = ability1;
}
public void setAbility2(String ability2) {
this.ability2 = ability2;
}
public void setAbility3String(String ability3) {
this.ability3 = ability3;
}
public void setAbility4(String ability4) {
this.ability4 = ability4;
}
public void setStrength(double strength) {
this.strength = strength;
}
public void setStrengthMultiplier(double strengthMultiplier) {
this.strengthMultiplier = strengthMultiplier;
}
public void setAgility(double agility) {
this.agility = agility;
}
public void setAgilityMultiplier(double agilityMultiplier) {
this.agilityMultiplier = agilityMultiplier;
}
public void setIntelligence(double intelligence) {
this.intelligence = intelligence;
}
public void setIntelligenceMultiplier(double intelligenceMultiplier) {
this.intelligenceMultiplier = intelligenceMultiplier;
}
public void setHealth(int health) {
this.health = health;
}
public void setMana(int mana) {
this.mana = mana;
}
public void setDamageMin(int damageMin) {
this.damageMin = damageMin;
}
public void setDamageMax(int damageMax) {
this.damageMax = damageMax;
}
public void setRange(int range) {
this.range = range;
}
public void setArmor(double armor) {
this.armor = armor;
}
public void setMovement(int movement) {
this.movement = movement;
}
} // End Character Class
Java has a Character class defined already (in package java.lang).
The Character class wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char.
EDIT - This package java.lang is imported by default and so the interface name clashes with the Character class defined in this package. Hence, the issue. It's always better to avoid using exactly same names anyway.
Related
I have like this json.I'm using Gson to parse it and convert it in my custom class object.Here is a my java classes
public class ResponseModel {
private int resultCode;
private Match match;
public Match getMatch() {
return match;
}
public int getResultCode() {
return resultCode;
}
}
public class Match {
private Team team1;
private Team team2;
private double matchTime;
public Team getTeam1() {
return team1;
}
public Team getTeam2() {
return team2;
}
private Long matchDate;
private String stadiumAdress;
public double getMatchTime() {
return matchTime;
}
public Long getMatchDate() {
return matchDate;
}
public String getStadiumAdress() {
return stadiumAdress;
}
}
public class Team {
private String teamName;
private String teamImage;
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getTeamImage() {
return teamImage;
}
public void setTeamImage(String teamImage) {
this.teamImage = teamImage;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getBallPosition() {
return ballPosition;
}
public void setBallPosition(int ballPosition) {
this.ballPosition = ballPosition;
}
private int score;
private int ballPosition;
}
I'm using Gson like this
ResponseModel responseModel = GsonUtil.fromJson(response.toString(), ResponseModel.class);
public class GsonUtil {
public static <T> T fromJson(String json, Class<T> c) {
return new Gson().fromJson(json, c);
}
public static String toJson(Object c) {
return new Gson().toJson(c);
}
}
Everything working perfect,I can convert my json to custom class.But I want to use enum class with team1 and team2. My goal is to convert like this enum class
MatchTeamType:
TEAM1 (1);
TEAM2 (2);
How I can rewrite my code with enum class?
Thanks
I have been trying to make three different extended classes from a superclass. The problem is that only the first extended class works fine while the other two gets an error when I name them, and its says they should be in their own file. I have looked around to see if someone had a similar problem, but nothing exactly like this. The extended class that is working is the first one called "Smycken".
here is the code:
abstract public class Vardesaker
{
private String name;
double value;
public Vardesaker(String name, double value)
{
this.name = name;
this.value = value;
}
public String getName()
{
return name;
}
abstract public double getValue();
}
class Smycken extends Vardesaker
{
private int adelstenar;
private String material;
public Smycken(String name, double value, int adelstenar, String material)
{
super(name, 0);
this.adelstenar = adelstenar;
this.material = material;
}
public int getadelstenar()
{
return adelstenar;
}
public String getMaterial()
{
return material;
}
public double getValue()
{
if(material.equalsIgnoreCase("guld"))
{
double sum = 2000 + (500*adelstenar);
value = sum*1.25;
}
else
{
double sum = 700 + (500*adelstenar);
value = sum*1.25;
}
return value;
}
}
public class Aktier extends Vardesaker
{
private double kurs;
private int amount;
public Aktier (String name, double value, int amount, double kurs)
{
super(name, 0);
this.kurs = kurs;
this.amount = amount;
}
public double getKurs()
{
return kurs;
}
public int getAmount()
{
return amount;
}
public double getValue()
{
double sum = (int) (amount*kurs);
value = sum*1.25;
return value;
}
}
public class Apparater extends Vardesaker
{
private double price;
private int slitage;
public Apparater(String name, double value, double price, int slitage)
{
super(name, 0);
this.price = price;
this.slitage = slitage;
}
public double getPrice()
{
return price;
}
public int getSlitage()
{
return slitage;
}
public double getValue()
{
double sum = price*(slitage/10);
value = sum*1.25;
return value;
}
}
It is not because of extends, it is because of public keyword for the other classes. If you create multiple class with public keyword then they should be in their own compilation unit.
Check this answer for why each public class should have separate file.
There is a simple rule - 1 public type (class,interface,enum) = 1 java file
I have been asked to implement a printDailyCost method which should call the getDailyCost method and format the value returned to two
decimal places. It should then print this value along with a £ sign.
So far I have:
public abstract class Suit {
private String colour;
private double dailyCost;
private int trouserLength;
private int jacketChestSize;
private boolean available;
private double totalPrice;
public Suit(String colour, double dailyCost, int trouserLength,
int jacketChestSize, boolean available, double totalPrice) {
super();
this.colour = colour;
this.dailyCost = dailyCost;
this.trouserLength = trouserLength;
this.jacketChestSize = jacketChestSize;
this.available = available;
this.totalPrice = totalPrice;
}
public String getColour() {
return colour;
}
public double getDailyCost() {
return dailyCost;
}
public int getTrouserLength() {
return trouserLength;
}
public int getJacketChestSize() {
return jacketChestSize;
}
public boolean isAvailable() {
return available;
}
public double getTotalPrice() {
return totalPrice;
}
public void setColour(String colour) {
this.colour = colour;
}
public void setDailyCost(double dailyCost) {
this.dailyCost = dailyCost;
}
public void setTrouserLength(int trouserLength) {
this.trouserLength = trouserLength;
}
public void setJacketChestSize(int jacketChestSize) {
this.jacketChestSize = jacketChestSize;
}
public void setAvailable(boolean available) {
this.available = available;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
public void calcTotalPrice(int numDaysHired){
this.totalPrice = dailyCost * numDaysHired;
}
public String printDailyCost() {
return printDailyCost();
}
}
My Question is how would I amend my printDailyCost method to call the getDailyCost method and format the value returned to two
decimal places then print with a £ sign?
Check this out:
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.UK);
System.out.println(format.format(getDailyCost()));
You can simply add them together and return it:
public String printDailyCost() {
return getDailyCost() + " £";
}
However I don't recommend to concatenate String with this way. Better use the following method using StringBuilder, that concatenates strings in the correct way:
public String printDailyCost() {
return (new StringBuilder().append(getDailyCost()).append(" £")).toString();
}
Or if you want to print it out to console, just do this:
System.out.println(getDailyCost() + " £");
I'm programming in a class and I need to have a variable from a different class. How can I do this?
package domein;
public class Speler
{
private String naam;
private String kleur;
private Sector sector;
private int Sector;
private int krediet = 10;
private int extraSchattingWaarde = 0;
private int nummer;
public Speler(String naam, String kleur, Sector sector)
{
setNaam(naam);
setKleur(kleur);
setSector(sector);
}
public String getNaam()
{
return this.naam;
}
public void setNaam(String naam)
{
//controle of het leeg is??
this.naam = naam;
}
public Sector getSector()
{
return this.sector;
}
private void setSector(Sector sector)
{
//tussen 1 en 4
this.sector = sector;
}
public String getKleur()
{
return this.kleur;
}
private void setKleur(String kleur)
{
//controle of het de beschikbare kleuren zijn
this.kleur = kleur;
}
public int getKrediet()
{
return this.krediet;
}
public void setKrediet(int krediet)
{
this.krediet = krediet;
}
public int getExtraSchattingWaarde()
{
return this.extraSchattingWaarde;
}
public void setExtraSchattingWaarde(int waarde)
{
this.extraSchattingWaarde = waarde;
}
}
This is the class where I need to get the variables and some methods. How can I make this class global?
Just a thing : this line is wrong private int Sector; because you can not use a class name as your variable name. This should hide your class visibility.
I assume this is an error and I continue the explanation.
In an other class you can instanciate this class and call the values. For example:
public class MyClass {
private Speler mySpeler = new Speler("AAA", "BBB", 3);
public MyClass() {}
public void myMethod() {
System.out.println(mySpeler.getKleur());
}
}
I have seen other array codes but here is what I got. I am trying to set the courseID in the CollegeCollege course in the array. I need to set the array in the student.java
public class CollegeCourse {
private static String courseID;
private static int creditHours;
private static char grade;
public static void setCourseID(String course){
courseID = course;
}
public static String getCourseID(){
return courseID;
}
public static void setCreditHours(int CH){
creditHours = CH;
}
public static int getCreditHours(){
return creditHours;
}
public static void setGrade(char g){
grade = g;
}
public static char getGrade(){
return grade;
}
public class Student {
private static int IDnumber;
private static CollegeCourse[] course = new CollegeCourse[5];
public static void setIDnumber(int x){
IDnumber = x;
}
public static int getIDnumber(){
return IDnumber;
}
public static String getCourse(int x){
return course[x].getCourseID();
}
public static void setCourse(CollegeCourse newCourse, int ID){
CollegeCourse.setCourseID = newCourse[ID];
}
}
It could seem like you are trying to code that the student takes course with id 5. Maybe your classes should have constructors taking arguments based on what ID the course has.
and I don't know what you need the fields to be static for, bt feel free to have them static if it is needed for some reason.
public class CollegeCourse {
private String courseID;
private int creditHours;
private char grade;
public CollegeCourse(String courseID) {
this.courseID = courseID;
}
...
public class Student {
...
private static CollegeCourse[] course = new CollegeCourse("5");
...
I think a better design would be this:
public class CollegeCourse {
private final String courseId;
private final int creditHours;
public CollegeCourse(final String courseId, int creditHours) {
this.courseId = courseId;
this.creditHours = creditHours;
}
public String getCourseId() {
return courseId;
}
public int getCreditHours() {
return creditHours;
}
#Override
public boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof CollegeCourse)) { return false; }
CollegeCourse cc = (CollegeCourse)o;
return courseId.equals(cc.courseId)
&& creditHours == cc.creditHours;
}
#Override
public int hashCode() {
int result = 17;
result = 31 * result + courseId.hashCode();
result = 31 * result + creditHours;
return result;
}
};
public enum Grade { A, B, C, D, E };
public class Student {
private final String id;
private final Map<CollegeCourse, Grade> course2GradeMap = new HashMap<>();
public Student(final String id) {
this.id = id;
}
public Grade getGrade(final CollegeCourse course) {
return couse2GradeMap.get(course);
}
public void addCollegeCourse(final CollegeCourse course, Grade grade) {
course2GradeMap.put(course, grade);
}
public Collection<CollegeCourse> getCollegeCourses() {
return Collections.unmodifiableCollection(course2GradeMap.values());
}
};
Use it in this way:
Student student = new Student("001");
student.addCollegeCourse(new CollegeCourse('alg', 100), Grade.A);
student.addCollegeCourse(new CollegeCourse('stat', 100), Grade.C);