how to output elements of an array by using the method "toString"? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

how to output elements of an array by using the method "toString"?

public void x(int p) { len++; points=new int[len]; points[len-1]=p; } public String toString() { String a=""; for(int i=0;i<points.length;i++) { a=" "+points[i]; } return " " + a; } public static void main(String[] args) { Program test=new Program(); test.x(2); test.x(4); System.out.println(test); } } I am trying to store some values into the array "points" by using the method x. After storing the values, I want to output these values. Instead of the values 2 and 4, I am only getting the value 4. How can I solve this problem without using ArrayList?

6th Dec 2019, 3:05 PM
Preet
8 Answers
+ 1
Its better to show full code.. Otherwise difficult to identify the missing logic.. Guessing that you are overwriting the array points values by 2nd test.x(4) call. Because you are using Points= new int[len];
6th Dec 2019, 4:16 PM
Jayakrishna 🇮🇳
+ 1
public class Program { int[] points=new int[10]; int len; public void x(int p) { //points=new int[len]; points[len++] =p; //points[len-1]=p; } public String toString() { String a=""; for(int i=0;i<len;i++) { a=a+points[i]; } return a; } public static void main(String[] args) { Program test=new Program(); test.x(2); test.x(4); test.x(7); System.out.println(test); } } Is this what you looking? output: 247
6th Dec 2019, 5:55 PM
Jayakrishna 🇮🇳
6th Dec 2019, 6:11 PM
Jayakrishna 🇮🇳
0
Is this your complete code?
6th Dec 2019, 3:17 PM
Avinesh
Avinesh - avatar
0
public class Program { int[] points; int len; public void x(int p) { len++; points=new int[len]; points[len-1]=p; } public String toString() { String a=""; for(int i=0;i<points.length;i++) { a=" "+points[i]; } return " " + a; } public static void main(String[] args) { Program test=new Program(); test.x(2); test.x(4); System.out.println(test); } }
6th Dec 2019, 4:46 PM
Preet
0
The length of the array should not be given
6th Dec 2019, 6:00 PM
Preet
0
Arrays are not dynamic means you can change array length at run time.. By your code you are overriding array values by creating new array so you last previous values by doing so..
6th Dec 2019, 6:05 PM
Jayakrishna 🇮🇳
0
Also possible: import java.util.Arrays; public String toString() { return Arrays.toString(points); }
6th Dec 2019, 10:46 PM
Denise Roßberg
Denise Roßberg - avatar