How to get an attribute/variable from a different class - java

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

Related

Parse Json with Gson in EnumClass

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

How to sort object array in Java [duplicate]

This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 6 years ago.
I have an object List with the name of cars and in this list I have some vehicle object. all objects values are different to each other. In all object here is custom field with the name of unit and in unit is another field with the name of unitType ... which is "T20" , "VT11" or any other ..
I want to sort this cars List according to unitType like:
if cars(0).getUnit().getUnitType().equals("T20") sort all the value first then other "VT11" and then all other...
How can I do this?? Is any suitable method in java?
my Unit class:
package com.vehicletracking.vtss.classes.bean;
import java.io.*;
public class Unit implements Serializable{
private int code;
private int unitId;
private String unitType; //X8, X1, X1+, VT10, VT200, SPT100
private Sim sim;
private String commType; //CSD, SMS, GPRS, AUTO
private int modemCode;
private long IMEI;
private String serialNo;
private InputReportProfile inputReportProfile;
private String firmware;
private String packageName;
private String password;
public Unit() {
}
public Unit(int unitId) {
this.unitId = unitId;
}
public Unit(int unitId, String unitType) {
this.unitId = unitId;
this.unitType = unitType;
}
public Unit(int unitId, String unitType, Sim sim) {
this.unitId = unitId;
this.unitType = unitType;
this.sim = sim;
}
public void setUnitId(int unitId) {
this.unitId = unitId;
}
public int getUnitId() {
return this.unitId;
}
public void setUnitType(String unitType) {
this.unitType = unitType;
}
public String getUnitType() {
return this.unitType;
}
public void setSim(Sim sim) {
this.sim = sim;
}
public void setCommType(String commType) {
this.commType = commType;
}
public void setModemCode(int modemCode) {
this.modemCode = modemCode;
}
public void setSerialNo(String serialNo) {
this.serialNo = serialNo;
}
public void setCode(int code) {
this.code = code;
}
public void setInputReportProfile(InputReportProfile inputReportProfile) {
this.inputReportProfile = inputReportProfile;
}
public void setPassword(String password) {
this.password = password;
}
public void setIMEI(long IMEI) {
this.IMEI = IMEI;
}
public Sim getSim() {
return this.sim;
}
public String getCommType() {
return commType;
}
public int getModemCode() {
return modemCode;
}
public String getSerialNo() {
return serialNo;
}
public int getCode() {
return code;
}
public InputReportProfile getInputReportProfile() {
return inputReportProfile;
}
public String getPassword() {
return password;
}
public long getIMEI() {
return IMEI;
}
public int hashCode() {
return unitId;
}
public boolean equals(Object obj) {
if (obj instanceof Unit) {
return this.unitId == ((Unit) obj).getUnitId();
}
return false;
}
public String toString() {
return this.unitId + "/" + this.unitType;
}
public String getFirmware() {
return firmware;
}
public void setFirmware(String firmware) {
this.firmware= firmware;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
}
Car List:
List cars;
From Java 8 Documentation for Comparable:
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.
Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.
According to above, you just have to implement Comparable, and provide an implementation for compareTo for your object. Collections.sort takes care of the rest.

Printing Out Character Stats to Console

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.

JsonMappingException during Json unmarshal in Spring

This is my POJO class:
public class OrdineIngressi {
private Integer spettacolo;
private Integer settore;
private Integer pv;
private List<OrdineIngresso> ingressi=new ArrayList<OrdineIngresso>();
public OrdineIngressi(Integer spettacolo, Integer settore, Integer pv,
List<OrdineIngresso> ingressi) {
super();
this.spettacolo = spettacolo;
this.settore = settore;
this.pv = pv;
this.ingressi = ingressi;
}
public OrdineIngressi() {
super();
}
public Integer getSpettacolo() {
return spettacolo;
}
public void setSpettacolo(Integer spettacolo) {
this.spettacolo = spettacolo;
}
public Integer getSettore() {
return settore;
}
public void setSettore(Integer settore) {
this.settore = settore;
}
public Integer getPv() {
return pv;
}
public void setPv(Integer pv) {
this.pv = pv;
}
public List<OrdineIngresso> getIngressi() {
return ingressi;
}
public void setIngressi(List<OrdineIngresso> ingressi) {
this.ingressi = ingressi;
}
public class OrdineIngresso {
private Integer tipoingresso;
private Integer abbonamento;
private int numero;
private Integer[] posti;
public OrdineIngresso() {
super();
}
public OrdineIngresso(Integer tipoingresso, Integer abbonamento,
int numero, Integer[] posti) {
super();
this.tipoingresso = tipoingresso;
this.abbonamento = abbonamento;
this.numero = numero;
this.posti = posti;
}
public Integer getTipoingresso() {
return tipoingresso;
}
public void setTipoingresso(Integer tipoingresso) {
this.tipoingresso = tipoingresso;
}
public Integer getAbbonamento() {
return abbonamento;
}
public void setAbbonamento(Integer abbonamento) {
this.abbonamento = abbonamento;
}
public Integer[] getPosti() {
return posti;
}
public void setPosti(Integer[] posti) {
this.posti = posti;
}
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
}
}
This is the ajax input:
{"spettacolo":1,"settore":1,"pv":1,"ingressi":[{"tipoingresso":1,"abbonamento":null,"numero":1,"posti":[]}]}
When the Controller tries to unmarshal a json input I got this:
nested exception is org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.bean.OrdineIngressi$OrdineIngresso]: can not instantiate from JSON object (need to add/enable type information?)
Why? There is a default constructor!
You're almost there, you just need to make your inner class static:
...
public static class OrdineIngresso {
private Integer tipoingresso;
...
}
IIRC it has to do with the fact that a non-args inner class constructor really isn't non-args and thus jackson doesn't have a general manner for instantiating these non-static inner classes.
Cheers,

I am looking to set and an array in java while setting a sub method in the array

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

Categories

Resources