0

Can anyone help me with this

I have written this snippet as this logic is used in one of my school projects. Please help me resolve this issue. https://code.sololearn.com/ch26rsbC240g/?ref=app https://code.sololearn.com/ch26rsbC240g/?ref=app

22nd Dec 2020, 12:58 PM
Abhiraj Ghumare
Abhiraj Ghumare - avatar
5 Answers
0
Now that you're asking for multiple objects, here is an example showing that: public class Q3 { static Q3[] obj; public int rno; public static void main(String[] args) { obj=new Q3[3]; for (int i = 0; i < obj.length; i++) { obj[i] = new Q3(); obj[i].rno=(int)(Math.random() * 50); } for (int i = 0; i < obj.length; i++) { System.out.println(obj[i].rno); } } } It sounds like you should look up how to use arrays.
23rd Dec 2020, 3:26 PM
Josh Greig
Josh Greig - avatar
+ 1
Add the commented line below and it'll run without throwing an exception: public class Q3 { static Q3[] obj; public int rno; public static void main(String[] args) { obj=new Q3[1]; obj[0] = new Q3(); // added this line so obj[0] won't be null. obj[0].rno=30; System.out.print(obj[0].rno); } }
22nd Dec 2020, 1:29 PM
Josh Greig
Josh Greig - avatar
+ 1
Nice that it worked. If you think I answered your question well, please hit the checkmark on it.
23rd Dec 2020, 5:20 PM
Josh Greig
Josh Greig - avatar
0
But I want to add multiple objects, not only 1 i.e. obj=new Q3[3]
22nd Dec 2020, 2:55 PM
Abhiraj Ghumare
Abhiraj Ghumare - avatar
0
Yea I also tried using loops and it worked
23rd Dec 2020, 3:46 PM
Abhiraj Ghumare
Abhiraj Ghumare - avatar