Java - Añadir datos a una ArrayList desde otra clase

 
Vista:
sin imagen de perfil
Val: 40
Ha aumentado su posición en 70 puestos en Java (en relación al último mes)
Gráfica de Java

Añadir datos a una ArrayList desde otra clase

Publicado por Fran (13 intervenciones) el 04/05/2021 12:20:21
Buenas!

El proyecto en el que estoy trabajando es sobre un concurso en el que unos profesores son elegidos como jueces aleatoriamente (también se introducen datos de estudiantes y los nombres de los colleges)

Clase Main: aquí no hay problema, tan solo es el menú al cual recurrir siempre (hay un login que he "deshabilitado" para testear el programa más fácilmente):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package worldskillscompetitionapp6;
 
import java.util.Scanner;
 
public class WorldSkillsCompetitionApp6
{
    public static void login()
    {
        Scanner sc = new Scanner(System.in);
 
        for(int i = 3; i > 0;)
        {
            System.out.println("Please, login. You have " +i +" attempts\n");
            System.out.print("Username: ");
            String username = sc.nextLine();
 
            System.out.print("Password: ");
            String password = sc.nextLine();
 
            //check in Login class username and password are correct
            Login login = new Login();
 
            boolean correctLogin = login.Login(username, password);
            if(correctLogin == true)
            {
                System.out.println("Succesful Login\n");
                break;
            }
            else
            {
                System.out.println("Incorrect username/password\n");
                i--;
                if(i == 0)
                {
                    System.out.print("You do not have more attempts.\n The programm will end.");
                    System.exit(0);
                }
            }
 
        }
    }
 
    public static void mainMenu()
    {
        Scanner sc = new Scanner(System.in);
        String userChoice;
 
        do
        {
            System.out.println("Menu:\n"
                    + "1. Colleges\n"
                    + "2. Students\n"
                    + "3. Teachers\n"
                    + "4. Judges\n"
                    + "5. Exit.");
            userChoice = sc.nextLine();
 
            switch(userChoice)
            {
                case "1":
                   College college = College.getInstance();
                   college.collegeMenu();
                   break;
 
                case "2":
                    Student student = Student.getInstance();
                    student.studentMenu();
                    break;
 
                case "3":
                    Teacher teacher = Teacher.getINSTANCE();
                    teacher.teacherMenu();
                    break;
 
                case "4":
                    Judge judge = Judge.getInstance();
                    judge.judgeMenu();
                    break;
 
                case "5":
                    System.out.println("\nSee you in the next\n"
                            + "WORLD SKILLS COMPETITION\n");
                    System.exit(0);
 
                default:
                    System.out.println("Please, enter a number between 1 and 5\n");
            }
        }while(userChoice != "5");
    }
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
 
        //login();
 
        mainMenu();
    }
 
}

Clase College: aquí tampoco tengo problema, pero es necesario añadir un College antes de añadir Students o Teachers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package worldskillscompetitionapp6;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
 
public class College
{
    private static final College INSTANCE = new College();
 
    College()
    {
    }
 
    public static College getInstance()
    {
        return INSTANCE;
    }
 
    Scanner sc =  new Scanner (System.in);
 
    private String collegeName;
    private String collegeID;
 
    List <College> listOfColleges =  new ArrayList<>();
    String userChoice;
 
    public String getCollegeName()
    {
        return collegeName;
    }
 
    public void setCollegeName(String collegeName)
    {
        this.collegeName = collegeName;
    }
 
    public String getCollegeID()
    {
        return collegeID;
    }
 
    public void setCollegeID(String collegeID)
    {
        this.collegeID = collegeID;
    }
 
    public void collegeMenu()
    {
        do
        {
            System.out.println("\nCollege Menu:\n"
                    + "1. List of Colleges\n"
                    + "2. Add College\n"
                    + "3. Delete College\n"
                    + "4. Back to Main Menu");
            userChoice = sc.nextLine();
 
            switch(userChoice)
            {
                case "1":
                    Listing();
                    break;
 
                case "2":
                    AddCollege();
                    break;
 
                case "3":
                    DeleteCollege();
                    break;
 
                case "4":
                    WorldSkillsCompetitionApp6.mainMenu();
            }
        }while(userChoice != "4");
 
    }
 
    public void Listing()
    {
        String listing = "";
 
        Iterator<College> it = listOfColleges.iterator();
        College checker;
 
        while(it.hasNext())
        {
            checker = it.next();
            listing =  listing + checker.getCollegeInfo();
            listing = listing + "\n";
        }
 
        if(listOfColleges.isEmpty())
        {
            System.out.println("No item has been added yet\n");
        }
        else
        {
            System.out.print("\nList Of Colleges:\n" +listing);
        }
 
    }
 
    public void AddCollege()
    {
        College tmpCollege = new College();
 
        System.out.print("\nCollege name: ");
        tmpCollege.setCollegeName(sc.nextLine());
 
        String collegeID = splitCollegeName(tmpCollege.getCollegeName());
 
        tmpCollege.setCollegeID(collegeID);
 
        listOfColleges.add(tmpCollege);
    }
 
    public String getCollegeInfo()
    {
        String msg = "College name: " +this.getCollegeName() +"\n";
        msg = msg + "College ID: " +this.getCollegeID();
        msg = msg + "\n";
 
        return msg;
    }
 
    public void DeleteCollege()
    {
        Scanner sc =  new Scanner (System.in);
        boolean collegeFound = false;
 
        System.out.print("\nPlease, enter the ID of the College which will be deleted: ");
 
        String searchCollegeID = sc.nextLine();
 
        Iterator<College> it = listOfColleges.iterator();
        College checker;
 
        while(it.hasNext() && collegeFound ==  false)
        {
            checker = it.next();
 
            if(checker.getCollegeID().equals(searchCollegeID))
            {
                collegeFound = true;
                String msg ="\n" +checker.getCollegeInfo() +"\n";
                msg += "This college has been deleted\n";
 
                System.out.println(msg);
 
                listOfColleges.remove(checker);
            }
            else
            {
            }
        }
 
        if(collegeFound ==  false)
        {
            System.out.println("The college with that ID was not found");
        }
    }
 
    public String splitCollegeName (String college)
    {
        String[] nameSplitted = college.split(" ");
        String tmpCollege1 = nameSplitted[0];
        String tmpCollege2 = nameSplitted[1];
        String collegeID = (tmpCollege1.substring(0, 2)
                +tmpCollege2.substring(0, 2)).toUpperCase();
 
        return collegeID;
    }
 
    public boolean checkCollege (String tmpCollege)
    {
        boolean collegeFound =  false;
        Iterator<College> it = listOfColleges.iterator();
        College checker;
 
        while(it.hasNext())
        {
            checker = it.next();
 
            if(checker.getCollegeName().equals(tmpCollege))
            {
                collegeFound = true;
            }
            else
            {
            }
        }
        return collegeFound;
 
    }
}

Clase Teacher: Aquí es donde empiezan las dudas. Los teachers se añaden bien, siempre y cuando el college esté añadido de antes. El problema es que los teachers son elegidos judges aleatoriamente y cuando son elegidos paso el ID del teacher a la clase Judge:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package worldskillscompetitionapp6;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
 
public class Teacher
{
    private static final Teacher INSTANCE = new Teacher();
 
    public Teacher()
    {
    }
 
    public static Teacher getINSTANCE()
    {
        return INSTANCE;
    }
 
    Scanner sc =  new Scanner (System.in);
 
    private String teacherCollege;
    private String teacherSubjProj;
    private String teacherID;
    private boolean isJudge;
 
    List <Teacher> listOfTeachers = new ArrayList<>();
    String userChoice;
 
    public String getTeacherCollege()
    {
        return teacherCollege;
    }
 
    public void setTeacherCollege(String teacherCollege)
    {
        this.teacherCollege = teacherCollege;
    }
 
    public String getTeacherSubjProj()
    {
        return teacherSubjProj;
    }
 
    public void setTeacherSubjProj(String teacherSubjProj)
    {
        this.teacherSubjProj = teacherSubjProj;
    }
 
    public String getTeacherID()
    {
        return teacherID;
    }
 
    public void setTeacherID(String teacherID)
    {
        this.teacherID = teacherID;
    }
 
        public boolean getIsJudge()
    {
        return isJudge;
    }
 
    public void setIsJudge(boolean isJudge)
    {
        this.isJudge = isJudge;
    }
 
    public void teacherMenu()
    {
        do
        {
            System.out.println("\nTeacher Menu:\n"
                    + "1. Add Teacher\n"
                    + "2. Back to Main Menu");
            userChoice = sc.nextLine();
 
            switch(userChoice)
            {
                case "1":
                    AddTeacher();
                    break;
 
                case "2":
                    WorldSkillsCompetitionApp6.mainMenu();
 
                default:
                    System.out.println("Please, enter a number between 1 and 2\n");
            }
        }while(userChoice != "2");
    }
 
    public void AddTeacher()
    {
        Teacher tmpTeacher = new Teacher();
 
        tmpTeacher.setTeacherCollege(teacherCollege());
 
        tmpTeacher.setTeacherSubjProj(teacherSubjProj());
 
        tmpTeacher.setTeacherID(teacherID(tmpTeacher.getTeacherCollege(),
                tmpTeacher.getTeacherSubjProj()));
 
        tmpTeacher.setIsJudge(isJudge(tmpTeacher.getTeacherID()));
 
        listOfTeachers.add(tmpTeacher);
    }
 
    public String teacherCollege()
    {
        System.out.print("\nTeacher College: ");
        String tmpTeacherCollege = sc.nextLine();
 
        if(!checkCollege(tmpTeacherCollege))
        {
            System.out.println("\nThis college has not been added yet.\n"
                    + "Please, add this college before entering a student.\n");
             WorldSkillsCompetitionApp6.mainMenu();
        }
        else
        {
        }
        return tmpTeacherCollege;
    }
 
    public String teacherSubjProj()
    {
        String tmpTeacherSubject = "";
        do
        {
            System.out.println("\nWhich project is the teacher in?\n"
                    + "1. Software Development\n"
                    + "2. Networking\n"
                    + "3. Web Design");
            tmpTeacherSubject = sc.nextLine();
 
            switch(tmpTeacherSubject)
            {
                case "1":
                    System.out.println("Software Development\n");
                    teacherSubjProj = "SOF";
                    break;
 
                case "2":
                    System.out.println("Networking\n");
                    teacherSubjProj = "NET";
                    break;
 
                case "3":
                    System.out.println("Web Design\n");
                    teacherSubjProj = "WEB";
                    break;
 
                default:
                    System.out.println("Please, enter a number between 1 and 3\n");
            }
        }while(!tmpTeacherSubject.equals("1") && !tmpTeacherSubject.equals("2") && !tmpTeacherSubject.equals("3"));
 
        return teacherSubjProj;
    }
 
    public String teacherID(String college, String subjProj)
    {
        College teacherCollege = College.getInstance();
        String teacherID = teacherCollege.splitCollegeName(college);
        teacherID += subjProj;
 
        if(checkCoach(teacherID) == false)
        {
            teacherID += "T";
            System.out.println("Take note of the teacher ID: " +teacherID);
        }
        else
        {
            System.out.println("This team has already a Coach assigned.\n"
                    + "Be sure to input the correct College and Project.\n");
 
            WorldSkillsCompetitionApp6.mainMenu();
        }
 
        return teacherID;
    }
 
    public static boolean checkCollege (String tmpTeacherCollege)
    {
        boolean exist = false;
        College checker = College.getInstance();
 
        if(checker.checkCollege(tmpTeacherCollege) == true)
        {
            exist = true;
        }
        else
        {
            exist = false;
        }
        return exist;
    }
 
    public boolean checkCoach(String tmpTeacherID)
    {
        Iterator <Teacher> it3 = listOfTeachers.iterator();
 
        Teacher checker;
        boolean teacherFound = false;
 
        while(it3.hasNext())
        {
            checker = it3.next();
 
            if(checker.getTeacherID().contains(tmpTeacherID))
            {
                teacherFound = true;
                System.out.println(checker.getTeacherID());
            }
        }
 
        return teacherFound;
    }
 
    public boolean isJudge(String tmpJudgeID)
    {
        boolean isJudge = false;
 
        int yesNo = (int) (Math.random()*2+1);
 
        if(yesNo == 1)
        {
            System.out.println(tmpJudgeID +" has been selected as a Judge\n");
 
            isJudge = true;
 
            Judge newJudge = new Judge();
 
            newJudge.Judge(tmpJudgeID);
        }
 
        return isJudge;
    }
 
}

Clase Judge: aquí es donde ocurre lo que no entiendo. Como se ve, hay una opcion para añadir Judges, pero esta opcion no debería existir porque los judges se deberian añadir con los datos enviados desde la clase Teacher. el método Judge() es el que utilizo para añadir al ArrayList de Judges los datos. Sin embargo, estos datos nunca se listan mientras que los añadidos manualmente si.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package worldskillscompetitionapp6;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
 
public class Judge
{
    private static final Judge INSTANCE = new Judge();
 
    public Judge()
    {
    }
 
    public static Judge getInstance()
    {
        return INSTANCE;
    }
 
    Scanner sc =  new Scanner (System.in);
 
    private String judgeID;
    private String sofJudge;
    private String netJudge;
    private String webJudge;
 
    List <Judge> listOfJudges = new ArrayList<>();
    String userChoice;
 
    public String getJudgeID()
    {
        return judgeID;
    }
 
    public void setJudgeID(String judgeID)
    {
        this.judgeID = judgeID;
    }
 
    public String getSofJudge()
    {
        return sofJudge;
    }
 
    public void setSofJudge(String sofJudge)
    {
        this.sofJudge = sofJudge;
    }
 
    public String getNetJudge()
    {
        return netJudge;
    }
 
    public void setNetJudge(String netJudge)
    {
        this.netJudge = netJudge;
    }
 
    public String getWebJudge()
    {
        return webJudge;
    }
 
    public void setWebJudge(String webJudge)
    {
        this.webJudge = webJudge;
    }
 
    public void judgeMenu()
    {
        do
        {
            System.out.println("\nJudge Menu:\n"
                    + "1. List of Judges\n"
                    + "2. Add Judge\n"
                    + "3. Back to Main Menu");
            userChoice = sc.nextLine();
 
            switch(userChoice)
            {
                case "1":
                    ListOfJudges();
                    break;
 
                case "2":
                    AddJudge();
                    break;
 
                case "3":
                    WorldSkillsCompetitionApp6.mainMenu();
 
                default:
                    System.out.println("Please, enter a number between 1 and 3\n");
            }
 
        }while(userChoice != "3");
    }
 
    public void Judge(String teacherID)
    {
        Judge tmpJudge = new Judge();
 
        tmpJudge.setJudgeID(teacherID);
        System.out.println("Hola " +tmpJudge.getJudgeID());
 
        listOfJudges.add(tmpJudge);
    }
 
    public void ListOfJudges()
    {
 
        String listing = "";
 
        Iterator<Judge> it = listOfJudges.iterator();
        Judge checker;
 
        while(it.hasNext())
        {
            checker = it.next();
            listing = listing + checker.getJudgeInfo();
            listing = listing + "\n";
        }
 
        if(listOfJudges.isEmpty())
        {
            System.out.println("No item has been added yet\n");
        }
        else
        {
            System.out.print("\nList Of Judges:\n" +listing);
        }
    }
 
    public String getJudgeInfo()
    {
        String msg = "Judge ID: " +this.getJudgeID() +"\n";
        msg+= "\n";
 
        return msg;
    }
 
    public void AddJudge()
    {
        Judge tmpJudge = new Judge();
 
        System.out.print("\nCollege name: ");
        tmpJudge.setJudgeID(sc.nextLine());
 
        listOfJudges.add(tmpJudge);
    }
}

Podrían ayudarme a averiguar donde está el error?

Muchas gracias de antemano.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 40
Ha aumentado su posición en 70 puestos en Java (en relación al último mes)
Gráfica de Java

Añadir datos a una ArrayList desde otra clase

Publicado por Fran (13 intervenciones) el 04/05/2021 12:43:26
Lo arreglé!! :D :D :D

En la clase Teacher, cuando se elige el Judge aleatoriamente y paso el ID a la clase Judge. En lugar de

1
2
3
Judge newJudge =  new Judge();
 
            newJudge.Judge(tmpJudgeID);

He llamado a la Instance de la clase Judge y se arregló:

1
2
3
Judge newJudge = Judge.getInstance();
 
            newJudge.Judge(tmpJudgeID);

Como diría Kase.O: "Hoy es mi renacimiento" jejejejejeje
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar