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?
8 Réponses
+ 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];
+ 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
+ 1
Preet
See this code...
https://code.sololearn.com/cWxiwhNqVkL4/?ref=app
0
Is this your complete code?
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);
}
}
0
The length of the array should not be given
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..
0
Also possible:
import java.util.Arrays;
public String toString()
{
return Arrays.toString(points);
}