Array Java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Array Java

Why this doesn't work class Jugador{ private String name; Jugador() { name = ""; } Jugador(String n) { name = n; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } } class Equipo{ private Jugador[] Js = new Jugador[5]; private String nombre; Equipo(){ nombre = ""; } Equipo(String nombre, String[] nombreJ) { this.nombre = nombre; for(int i = 0; i < 2; ++i) { Js[i].setName(nombreJ[i]); } } public void print() { System.out.println("Equipo: "+nombre); for(int i = 0; i < 2; ++i) { System.out.println("Jugador #"+i+": "+Js[i].getName()); } System.out.println(); } } public class Anything { public static void main(String[] args) { Equipo Madrid = new Equipo("R", new String[]{"M", "M"}); Equipo Barcelona = new Equipo("B", new String[]{"F", "F"}); Madrid.print(); Barcelona.print(); } } 🙃

5th Jan 2023, 5:37 PM
Marco Cárdenas
Marco Cárdenas - avatar
3 Answers
+ 2
You declared array and it's size but not initialized it. for(int i = 0; i < 2; ++i) { Js[i] = new Jugador(nombreJ[i]); // use this, instead of //Js[i].setName(nombreJ[i]); }
5th Jan 2023, 6:38 PM
Jayakrishna 🇮🇳
+ 1
What error you getting? What is expected output? Mention details.. Instead of code pasting, it's better to save and share link. That helps to debug easily...
5th Jan 2023, 6:28 PM
Jayakrishna 🇮🇳
0
If I don't use class Jugador as an Array, it works but I need the Jugador array
5th Jan 2023, 5:38 PM
Marco Cárdenas
Marco Cárdenas - avatar