I know this must be a fundamental design problem because I clearly can't do this. I want to call the ownGrokk, ownTyce, etc methods from another class depending on the value of the integer assigned to OwnedSpirits(int). This in turn fills arrays.
The problem is, I do this multiple times, and doing it from another class it seems like I have to make a new object every time to pass the new int argument, and doing so resets the value of spiritInstance. And, since that resets to zero, the arrays don't fill properly. I try to print out my array values later and I get an "ArrayIndexOutOfBoundsException".
public class OwnedSpirits {
private int spiritTypeInt = 0;
public static int spiritInstance=0;
public static int[] spiritarray = new int[9];
public static String[] spiritName = new String[9];
public static int[] party = new int[3];
public OwnedSpirits(int spiritcall){
if(spiritcall == 1){
ownGrokk();
}
if(spiritcall == 2){
ownRisp();
}
if(spiritcall == 3){
ownTyce();
}
if(spiritcall == 4){
ownDaem();
}
if(spiritcall == 5){
ownCeleste();
}
}
private void ownGrokk(){
spiritName[spiritInstance] = "Grokk";
spiritInstance++;
}
private void ownRisp(){
spiritName[spiritInstance] = "Risp";
spiritInstance++;
}
private void ownDaem(){
spiritName[spiritInstance] = "Daem";
spiritInstance++;
}
private void ownCeleste(){
spiritName[spiritInstance] = "Celeste";
spiritInstance++;
}
private void ownTyce(){
spiritName[spiritInstance] = "Tyce";
spiritInstance++;
}
and this code is in another class, where it attempts to call the methods to fill the array
buttonConfirm.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
if(xcounter==3){
for(x=0; x<3; x++){
if(setdaemtrue == true){
new OwnedSpirits(4);
}
if(setrisptrue == true){
new OwnedSpirits(2);
}
if(setcelestetrue == true){
new OwnedSpirits(5);
}
if(settycetrue == true){
new OwnedSpirits(3);
}
if(setgrokktrue == true){
new OwnedSpirits(1);
}
}
}
}
});
and finally in yet another class:
System.arraycopy(OwnedSpirits.spiritName, 0, partylist, 0, 3);
#Override
public void show() {
System.out.println(partylist[0]);
System.out.println(partylist[1]);
System.out.println(partylist[2]);
spiritlist.setItems(partylist);
table.add(spiritlist);
table.setFillParent(true);
stage.addActor(table);
}
If the last part is confusing, it's because I am using libgdx. the print statements are there just to try to figure out why my list was having an error
I can show you what I would do to handle Spirits, and Parties.
The Spirit class, contains name and current party its assigned to:
package com.stackoverflow.spirit;
public class Spirit {
private String name;
private Party party;
private SpiritType type;
private static int id = 0;
public static enum SpiritType {
Grokk, Risp, Tyce, Daem, Celeste
};
public Spirit(String name, SpiritType type) {
create(name, type);
}
public Spirit(SpiritType type) {
create(null, type);
}
// This is to handle Java inexistance of default parameter values.
private void create(String name, SpiritType type)
{
Spirit.id++;
this.name = (name == null) ? (type.name() + " " + id) : name;
this.type = type;
}
public String getName() {
return name;
}
public Party getParty() {
return party;
}
public SpiritType getType() {
return type;
}
/**
* Used internally by #see Party
* #param party the party this Spirit belongs
*/
public void setParty(Party party) {
this.party = party;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString()
{
return this.name;
}
}
Finally the Party class, contains a set of Spirits, you can add and remove Spirits from the party.
package com.stackoverflow.spirit;
import java.util.HashSet;
public class Party {
private HashSet<Spirit> spirits = new HashSet<Spirit>();
private static int id = 0;
private String name = "Party " + Party.id++;;
public Party() {
}
public Party(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void add(Spirit spirit) {
if (!spirits.contains(spirit)) {
spirits.add(spirit);
if (spirit.getParty() != null) {
//Remove from previous party to update the other party set
spirit.getParty().remove(spirit);
}
spirit.setParty(this);
} else {
// throw new SpiritAlreadyOnParty();
}
}
public void remove(Spirit spirit)
{
if (spirits.contains(spirit))
{
spirit.setParty(null); // You could create a default empty party for "Nature/Neutral" Spirits perhaps :)
spirits.remove(spirit);
}
else {
//throw new SpiritNotInParty();
}
}
public boolean isOnParty(Spirit spirit) {
return spirits.contains(spirit);
}
public ArrayList<Spirit> getSpirits()
{
return new ArrayList<Spirit>(spirits);
}
public int getPartySize() {
return spirits.size();
}
public String getPartyInfo()
{
StringBuilder builder = new StringBuilder();
builder.append("Party:" + this.name + " Size:" + this.spirits.size() + "\n");
for (Spirit s : spirits)
{
builder.append(s.getName() + "\n");
}
return builder.toString();
}
#Override
public String toString()
{
return this.name;
}
}
Here I use the Spirit and Party classes, you could add more functionality, like properties for party strength, magic buffs on the party, etc:
package com.stackoverflow.spirit;
import com.stackoverflow.spirit.Spirit.SpiritType;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
Party griffindor = new Party("Griffindor"), slytherin = new Party(
"Slytherin");
// You can also do for (SpiritType type : SpiritType.values() then
// type.ordinal()
for (int i = 0; i < SpiritType.values().length; i++) {
griffindor.add(new Spirit(SpiritType.values()[i]));
slytherin.add(new Spirit(SpiritType.values()[i]));
}
Spirit mySpirit = new Spirit("NotAHPFan", SpiritType.Celeste);
slytherin.add(mySpirit);
System.out.println("Name of party:" + mySpirit.getParty().getName());
System.out.println("Is on griffindor?:"
+ griffindor.isOnParty(mySpirit));
// What now?
griffindor.add(mySpirit);
System.out.println("Is " + mySpirit.getName() + " on "
+ slytherin.getName() + "?:" + slytherin.isOnParty(mySpirit));
System.out.println(mySpirit.getName() + " is now on "
+ mySpirit.getParty() + "\n");
System.out.println(griffindor.getPartyInfo());
System.out.println(slytherin.getPartyInfo());
}
}
P.D: I'm not a HP fan.
Related
I have three classes called League, Team and Player, League has an array with teams, and I have a method called showLeagueTable that shows team sorted by ranking(which is a method that exists in the Team class) and the class Team has an array of players.
League.java
public class League<T extends Team> {
public String name;
private List<T> teams = new ArrayList<>();
public League(String name) {
this.name = name;
}
public boolean add(T team) {
if (teams.contains(team)) {
return false;
}
return teams.add(team);
}
public void showLeagueTable() {
Collections.sort(this.teams);
for (T t: teams) {
System.out.println(t.getName() + ": " + t.ranking());
}
}
}
Team.java
public class Team<T extends Player> implements Comparable<Team<T>> {
private String name;
int played = 0;
int won = 0;
int lost = 0;
int tied = 0;
private ArrayList<T> members = new ArrayList<>();
public Team(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean addPlayer(T player) {
if (members.contains(player)) {
System.out.println(player.getName() + " is already on this team");
return false;
} else {
members.add(player);
System.out.println(player.getName() + " picked for team " + this.name);
return true;
}
}
public int numPlayers() {
return this.members.size();
}
public void matchResult(Team<T> opponent, int ourScore, int theirScore) {
String message;
if (ourScore > theirScore) {
won++;
message = " beat ";
} else if (ourScore == theirScore) {
tied++;
message = " drew with ";
} else {
lost++;
message = " lost to ";
}
played++;
if (opponent != null) {
System.out.println(this.getName() + message + opponent.getName());
opponent.matchResult(null, theirScore, ourScore);
}
}
public int ranking() {
return (won * 2) + tied;
}
#Override
public int compareTo(Team<T> team) {
return Integer.compare(team.ranking(), this.ranking());
}
}
Player.java
public class Player {
private String name;
public Player(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
but in the line Collections.sort(this.teams); from the class League, I got the warning Unchecked method 'sort(List<T>)' invocation, I have read that maybe the problems is that I haven't implemented the Comparable interface in my class Team with a Type, but I did it you can see it at the line:
public class Team<T extends Player> implements Comparable<Team<T>>
can someone help me, please, thanks!
here a fully workable code for you specific issue :
it removes warning and errors.
phase 1 : remove comparable behaviour
phase 2 : try to compile without warning
phase 3 : try with a real new allocation : imporant, because, if you do not do anything new, T generics are not used, and you can not detect errors.
phase 4 : adding comparable behaviour.
final source [ see A) B) and C) mistakes in source]
League.java
package test;
import java.util.ArrayList;
import java.util.List;
import test.Team;
import java.util.Collections;
// -- A) missing precision about Team , Team based on Player
// -- public class League<T extends Team>
public class League<T extends Team<E>, E extends Player>
{
public String name;
// B) ! miss <T> after new :
// private List<T> teams = new ArrayList<>();
private List<T> teams = new ArrayList<T>();
public League(String name) {
this.name = name;
}
public boolean add(T team) {
if (teams.contains(team)) {
return false;
}
return teams.add(team);
}
public void showLeagueTable() {
Collections.sort(this.teams);
for (T t: teams) {
System.out.println(t.getName() + ": " + t.ranking());
}
}
}
Team.java
package test;
import java.util.ArrayList;
public class Team<T extends Player> implements Comparable<Team<T>> {
private String name;
int played = 0;
int won = 0;
int lost = 0;
int tied = 0;
// C) !! MISS <T> after new ArrayList
// private ArrayList<T> members = new ArrayList<>();
private ArrayList<T> members = new ArrayList<T>();
#Override
public int compareTo(Team<T> team) {
return Integer.compare(team.ranking(), this.ranking());
}
public Team(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean addPlayer(T player) {
if (members.contains(player)) {
System.out.println(player.getName() + " is already on this team");
return false;
} else {
members.add(player);
System.out.println(player.getName() + " picked for team " + this.name);
return true;
}
}
public int numPlayers() {
return this.members.size();
}
public void showPlayers() {
for (T element : members) {
System.out.println(element.getName());
}
}
public void matchResult(Team<T> opponent, int ourScore, int theirScore) {
String message;
if (ourScore > theirScore) {
won++;
message = " beat ";
} else if (ourScore == theirScore) {
tied++;
message = " drew with ";
} else {
lost++;
message = " lost to ";
}
played++;
if (opponent != null) {
System.out.println(this.getName() + message + opponent.getName());
opponent.matchResult(null, theirScore, ourScore);
}
}
public int ranking() {
return (won * 2) + tied;
}
}
Player.java
package test;
public class Player {
private String name;
public Player(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Test.java
package test;
import test.League;
import test.Team;
import test.Player;
public class Test {
Player p1;
Player p2;
Player p3;
Player p4;
Player p5;
Player p6;
Player p7;
Player p8;
Player p9;
Team<Player> t1;
Team<Player> t2;
Team<Player> t3;
Team<Player> t4;
public void test() {
System.out.println("RUNNING TEST");
p1=new Player("Mike");
p2=new Player("John");
p3=new Player("Jenny");
p4=new Player("Sunny");
p5=new Player("Mike");
p6=new Player("Jeremy");
p7=new Player("Gwen");
p8=new Player("Hector");
p9=new Player("Henry");
t1=new Team<Player>("Team1");
t2=new Team<Player>("Team2");
t3=new Team<Player>("Team3");
t4=new Team<Player>("Team4");
t1.addPlayer(p1);
t1.addPlayer(p2);
t2.addPlayer(p3);
t2.addPlayer(p4);
t2.addPlayer(p5);
t3.addPlayer(p6);
t3.addPlayer(p7);
t4.addPlayer(p8);
t4.addPlayer(p9);
// test show players
t1.showPlayers();
System.out.println("------------");
System.out.println("num players in team is "+t1.numPlayers());
System.out.println("---adding team in league ---------");
League<Team<Player>, Player> g1=new League<Team<Player>, Player>("League 1");
g1.add(t1);
g1.add(t2);
League<Team<Player>, Player> g2=new League<Team<Player>, Player>("League 2");
g2.add(t3);
g2.add(t4);
System.out.println("---settings results ---------");
t1.matchResult(t2, 2, 8);
t2.matchResult(t1, 1, 7);
t3.matchResult(t4, 4, 5);
t3.matchResult(t4, 4, 0);
System.out.println("-----League 1---------");
g1.showLeagueTable();
System.out.println("-----League 2---------");
g2.showLeagueTable();
}
}
Main.java
import test.Test;
public class Main
{
public static void main(String[] args) {
System.out.println("running MAIn");
Test test = new Test();
test.test();
}
}
Im trying to create a small character builder, using inheritance. i have CreateCharacter CharacterRace then a Dwarf class. i made a variable with type CharacterRace in CreateCharacter and a variable with type Dwarf in CharacterRace. i have an object of CreateCharacter in my main method demo and its not letting me call the methods from the Dwarf class, to make a dwarf character. im thinking ineed to pass a dwarf object in characterRace? im just not sure how. heres my code: (its a bit long my apologies)
package characterCreation;
public class CreateCharacter {
private CharacterClass characterClass;
private CharacterRace characterRace;
private Name name;
public CreateCharacter(String characterName,CharacterClass characterClass,CharacterRace characterRace) {
this.name = new Name(characterName);
this.characterClass = characterClass;
this.characterRace = characterRace;
}
public CreateCharacter(){
}
public CharacterClass getCharacterClass() {
return characterClass;
}
public void setCharacterClass(CharacterClass characterClass) {
this.characterClass = characterClass;
}
public CharacterRace getCharacterRace() {
return characterRace;
}
public void setCharacterRace(CharacterRace characterRace) {
this.characterRace = characterRace;
}
public Name getName(){
return name;
}
public void setName(Name name){
this.name = name;
}
#Override
public String toString() {
return "CreateCharacter [name=" + name + ", characterRace=" + characterRace + ", characterClass="
+ characterClass + "]";
}
}
package characterCreation;
public class CharacterRace {
protected String raceName;
protected double mana;
protected double hp;
private Dwarf dwarf;
public CharacterRace(String raceName,double mana, double hp) {
this.raceName = raceName;
this.mana = mana;
this.hp = hp;
}
public CharacterRace(){
}
public String getRaceName() {
return raceName;
}
public Dwarf getDwarf() {
return dwarf;
}
public void setDwarf(Dwarf dwarf) {
this.dwarf = dwarf;
}
public double getMana() {
return mana;
}
public double getHp() {
return hp;
}
#Override
public String toString() {
return "CharacterRace [dwarf=" + dwarf + "]";
}
}
package characterCreation;
public class Dwarf extends CharacterRace {
public Dwarf(String raceName,double mana, double hp) {
super(raceName,mana,hp);
}
public double getMana() {
mana = 5;
return mana;
}
public double getHp() {
hp = 10;
return hp;
}
public String getRaceName(){
return raceName = "Dwarf";
}
#Override
public String toString() {
return "Dwarf [mana=" + mana + ", hp=" + hp + ", getRaceName()=" + getRaceName() + "]";
}
}
package characterCreation;
import java.util.Scanner;
public class CharacterDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CreateCharacter create = new CreateCharacter();
System.out.println("Choose your Race: ");
String userRace = input.next();
create.setName(new Name("Daxel"));
//create.setCharacterRace(race);
System.out.println(create.getName());
//Dwarf dwarf = new Dwarf();
System.out.println(create.getCharacterRace().getDwarf().getRaceName());
//System.out.println(create.getCharacterRace().setDwarf(new Dwarf("dwarf",10,5)));
}
}
You have to call setCharacterRace() on create; then call setDwarf() on the characterRace; otherwise create.getCharacterRace() would be null and create.getCharacterRace().getDwarf() would throw NullPointerException.
I don't understand the logic behind your code, but try the code below:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CreateCharacter create = new CreateCharacter();
System.out.println("Choose your Race: ");
String userRace = input.next();
create.setName(new Name("Daxel"));
//***********new code starts******
CharacterRace myRace = new CharacterRace(userRace, 20, 9);
myRace.setDwarf(new Dwarf("dwarf",10,5));
create.setCharacterRace(myRace);
//***********new code ends********
//create.setCharacterRace(race);
System.out.println(create.getName());
//Dwarf dwarf = new Dwarf();
System.out.println(create.getCharacterRace().getDwarf().getRaceName());
//System.out.println(create.getCharacterRace().setDwarf(new Dwarf("dwarf",10,5)));
}
I've been having some issues with this program. I have to test out using a driver class each method, but I can't seem to understand what I should do when the parameters are strings.
I had an example for int parameters but the example never showed anything on string parameters and how to convert. Using null makes my driver class run but putting an int or string won't.
What can I do to convert this correctly, so it can display whatever I have in the no parameter constructor?
public class StudentListing
{
private String name;
private String number;
public StudentListing(String n, String num)
{
name = n;
number = num;
}
public StudentListing()
{
name = null;
number = null;
}
public String toString()
{
return("Name is " + name +
"\nNumber is " + number + "\n");
}
public void show()
{
System.out.println(toString());
}
public StudentListing Clone()
{
StudentListing clone = new StudentListing (name, number);
return clone;
}
public int compareTo(String targetKey)
{
return (name.compareTo(targetKey));
}
public void input()
{
name = JOptionPane.showInputDialog("Enter a name");
number = JOptionPane.showInputDialog("Enter a number");
}// end of StudentListing
}//end of class
public class StudentListingDriver
{
public static void main(String[] args)
{
StudentListing s1 = new StudentListing();
StudentListing s2 = new StudentListing(null,null);
System.out.println(s1);
s1.input();
StudentListing s3 = s2.clone();
s1.show();
}
}
You can have default values and make the no-args constructor call the other constructor.
Use Integer.parseInt(); to convert from a String to an Integer.
You also need to check the conversion for exceptions.
Like this:
public class StudentListing {
private String name;
private int number;
public StudentListing(String n, int num) {
name = n;
number = num;
}
public StudentListing() {
this("defaultName", 0);
}
public String toString() {
return ("Name is " + name + "\nNumber is " + number + "\n");
}
public void show() {
System.out.println(toString());
}
public StudentListing Clone() {
StudentListing clone = new StudentListing(name, number);
return clone;
}
public int compareTo(String targetKey) {
return (name.compareTo(targetKey));
}
public void input() {
name = JOptionPane.showInputDialog("Enter a name");
number = Integer
.parseInt(JOptionPane.showInputDialog("Enter a number"));
}
}
The tester:
public class StudentListingDriver {
public static void main(String[] args) {
StudentListing s1 = new StudentListing();
StudentListing s2 = new StudentListing(null, 0);
System.out.println(s1);
s1.input();
StudentListing s3 = s2.Clone();
s1.show();
}
}
I need help removing a specific object from an arraylist. I'm creating objects with a unique ID and grade for each object.I'm trying to use this unique ID to remove an object from the arraylist, but am having trouble figuring out why my code isn't working. I have my main Driver class, a superclass, and a subclass.
The subclass is where the object information is passed from and extends the superclass. I thought that since the subclass is extended, it would be able to be defined from there.
The problem that is occurring is line 49 of the superclasss. Eclipse says that getStudentID isn't defined in the class.
I am trying to modify code that my instructor provided in order to locate this unique ID that an object in the arraylist has. I believe I did everything correctly, but the method "locationPerson" doesn't seem to see the getStudentID() method in the subclass.
Here is the code. Any help would be appreciated!
Subclass
public class StudentEnrollee extends ClassSection{
private int grade;
private String studentID;
StudentEnrollee() {
setStudentID("000-000");
setGrade(0);
}
StudentEnrollee(String ID, int theGrade) {
setStudentID(ID);
setGrade(0);
}
//STUDENT ID
public String getStudentID() {
return studentID;
}
public void setStudentID(String theStudentID) {
this.studentID = theStudentID;
}
//STUDENT GRADE
public int getGrade() {
return grade;
}
public void setGrade(int studentGrade) {
this.grade = studentGrade;
}
public String toString() {
return("Student ID : " + studentID + "\n" +
"Student Grade: " + grade);
}
}
Superclass
import java.util.ArrayList;
import java.util.List;
public class ClassSection {
private int crn, courseNumber, capacity, enrollment, ID, student;
private String departmentCode, courseMode, meetingDay, meetingTime;
//CONSTRUCTOR
ClassSection() {
setCrn(0);
setDepartmentCode("");
setCourseNumber(0);
setCourseMode("");
setMeetingDay("");
setMeetingTime("");
setCapacity(0);
setEnrollment(0);
setID(0);
}
ClassSection(int crn, String departmentCode, int courseNumber, String courseMode, String meetingDay, String meetingTime, int capacity, int enrollment, int ID) {
setCrn(crn);
setDepartmentCode(departmentCode);
setCourseNumber(courseNumber);
setCourseMode(courseMode);
setMeetingDay(meetingDay);
setMeetingTime(meetingTime);
setCapacity(capacity);
setEnrollment(enrollment);
setID(ID);
}
//STUDENT ENROLL ARRAY
List < StudentEnrollee > studentList = new ArrayList < StudentEnrollee > ();
public int getStudent() {
return student;
}
public void addStudent(StudentEnrollee studentObject) {
studentList.add(studentObject);
}
//LOCATING PERSON
public ClassSection locatePerson(String getStudentID) {
for (ClassSection personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
//Delete person
public void deletePerson(String studentID) {
ClassSection personObject = locatePerson(studentID); // we'll use our locatePerson method find the index of a Person with a given socSecNum.
if (personObject != null) studentList.remove(personObject); // if element i contains the target SSN, remove it.
}
//DISPLAY LIST OF ENROLLEE
public void displayListV1() {
for (int i = 0; i < studentList.size(); i++) // the old way
{
System.out.println(studentList.get(i) + "\n");
}
}
//CRN
public int getCrn() {
return crn;
}
void setCrn(int classCrn) {
this.crn = classCrn;
}
//DEPARTMENT CODE
public String getDepartmentCode() {
return departmentCode;
}
void setDepartmentCode(String classDepartmentCode) {
this.departmentCode = classDepartmentCode;
}
//COURSE NUMBER
public int getCourseNumber() {
return courseNumber;
}
void setCourseNumber(int classCourseNumber) {
this.courseNumber = classCourseNumber;
}
//COURSE LOCATION
public String getCourseMode() {
return courseMode;
}
public void setCourseMode(String classCourseMode) {
this.courseMode = classCourseMode;
}
//MEETING DAY
public String getMeetingDay() {
return meetingDay;
}
public void setMeetingDay(String classMeetingDay) {
this.meetingDay = classMeetingDay;
}
//MEETING TIMES
public String getMeetingTime() {
return meetingTime;
}
public void setMeetingTime(String classMeetingTime) {
this.meetingTime = classMeetingTime;
}
//CAPACITY
public int getCapacity() {
return capacity;
}
public void setCapacity(int classCapacity) {
this.capacity = classCapacity;
}
//ENROLLMENT
public int getEnrollment() {
return enrollment;
}
public void setEnrollment(int classEnrollment) {
this.enrollment = classEnrollment;
}
//INSTRUCTOR ID
public int getID() {
return ID;
}
public void setID(int instructorID) {
this.ID = instructorID;
}
//TO STRING METHOD
public String toString() {
return ("CRN :" + crn + "\n" +
"Department :" + departmentCode + "\n" +
"Course Number :" + courseNumber + "\n" +
"Instructional mode :" + courseMode + "\n" +
"Meeting days :" + meetingDay + "\n" +
"Meeting times :" + meetingTime + "\n" +
"Capacity :" + capacity + "\n" +
"Enrollment :" + enrollment + "\n" +
"Instructor’s ID :" + ID + "\n");
}
}
Driver
public class ClassDriver {
public static void main(String[] args) {
ClassSection firstInstance = new ClassSection(20008, "CHM", 000, "Online", "N/A", "N/A", 30, 21, 231);
ClassSection secondInstance = new ClassSection();
ClassSection addToList = new ClassSection();
StudentEnrollee studentObj1 = new StudentEnrollee();
StudentEnrollee studentObj2 = new StudentEnrollee();
StudentEnrollee studentObj3 = new StudentEnrollee();
studentObj1.setGrade(5);
studentObj1.setID(230);
studentObj2.setGrade(76);
studentObj2.setID(45);
studentObj3.setGrade(2);
studentObj3.setID(34);
addToList.addStudent(studentObj1);
addToList.addStudent(studentObj2);
addToList.addStudent(studentObj3);
addToList.deletePerson("45");
addToList.displayListV1();
System.out.println(firstInstance.toString());
System.out.println(secondInstance.toString());
}
}
I think it should be:
public StudentEnrollee locatePerson(String getStudentID) {
for (StudentEnrollee personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
You are trying to use a method from subclass in superclass, so you got the error that this method is not defined. You can use all method of superclass in subclasses, but it doesn't work another way.
The getStudentID() method is declared in class StudentEnrollee. In the code below, personObject, which is defined as a ClassSection object, does not have access to it.
public ClassSection locatePerson(String getStudentID) {
for (ClassSection personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
The solution can vary based on your program logic, but the straightforward way is to replace ClassSection with StudentEnrollee:
public StudentEnrollee locatePerson(String getStudentID) {
for (StudentEnrollee personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
I've got a problem with my programm. When i try to compile following i just receive the message:
Tutorium.java:15: error: <identifier> expected
public void settName(vorlesung.lectureName) {
^
So my Code:
Tutorium.java
public class Tutorium {
private Vorlesung vorlesung;
public String tName;
private int tNumber;
public int gettNumber() {
return this.tNumber;
}
public String gettName() {
return this.tName;
}
public void settName(vorlesung.lectureName) {
this.tName = vorlesung.lectureName;
}
public String toString() {
return (this.tName + ", " + this.tNumber);
}
public Tutorium(int tNumber){
this.tNumber = tNumber; } }
Vorlesung.java
public class Vorlesung {
public String lectureName;
private int lectureNumber;
private int lecture;
private Dozent dozent;
private String lecturerlName;
public String getlectureName(){
return this.lectureName;
}
public int lectureNumber(){
return this.lectureNumber;
}
public int lecture(){
return this.lecture;
}
public String getlecturer(){
this.lecturerlName = dozent.lecturerlName;
return this.lecturerlName;
}
public String toString() {
return (this.lectureName + ", " + this.lectureNumber);
}
public Vorlesung(String lectureName, int lecture) {
this.lectureName = lectureName;
this.lecture = lecture +1;
this.lectureNumber = this.lecture -1;
this.lecturerlName = lecturerlName;
}}
My Main-Method:
public class MainVorlesung {
public static void main(String[] args) {
Student student = new Student("STUDENTNAME", "STUDENTLASTNAME", 178, 1);
Vorlesung vorlesung = new Vorlesung("Programmieren", 13341);
Tutorium tutorium = new Tutorium(3);
Dozent dozent = new Dozent("LECTURERFIRSTNAME", "LECTURERLASTNAME", 815);
System.out.println(student.toString());
System.out.println(vorlesung.toString());
System.out.println(tutorium.toString());
System.out.println(dozent.toString());
}}
My goal is to set the value of tName equal the value of vorlesung.lectureName.
Why can't i do this that way?
I appreciate every help. :)
Thanks
For methods, the arguments that you pass in must have a declared value.
In this case, a String. So you need to change your method to this:
public void settName(String newLectureName) {
this.tName = newLectureName;
}
Read more about what a java method is and how to create one here: http://www.tutorialspoint.com/java/java_methods.htm
Change settName to
public void settName(String name) {
this.tName = name;
}
Since your goal is:
My goal is to set the value of tName equal the value of vorlesung.lectureName.
You should get rid of the setName method entirely since it will depend entirely on the vorlesung field and so should not be changeable. You should also get rid of the tName field, and instead change getName() to:
public class Tutorium {
private Vorlesung vorlesung;
// public String tName; // get rid of
private int tNumber;
public String gettName() {
if (vorlesung != null) {
return vorlesung.getlecturer();
}
return null; // or throw exception
}
// *** get rid of this since you won't be setting names
// public void settName(Vorlesung vorlesung) {
// this.tName = vorlesung.lectureName;
// }
I have just now noticed that your Tutorium class does not have and absolutely needs a setVorlesung(...) method.
public void setVorlesung(Vorlesung vorlesung) {
this.vorlesung = vorlesung;
}