Here is the code I thought should work but I am missing something:
public String arrayToString(int[] nums){
String str;
int[] results = new int[nums.length];
for(int i = 0; i < nums.length; i ){
String string = "[1 , 2, 3, 4]";
}
return str;
}
This should return all the values of nums with spaces or do I need to switch the string?
I have tried to use the toString
option which for some reason is not allowed in the IDE I am using as it is not using JRE 17 I believe the error message said. So that was not an option since I could not use java.lang.String
.
CodePudding user response:
You're actually doing quite nothing to reach your goal, you don't use nums
values, and have defined a strange String string = "[1 , 2, 3, 4]";
You need to append all the values of nums
to reach your goal, here are some ways
An array-style with existing method
// '[1, 5, 8, 98]'
public static String arrayToString(int[] nums) {
return Arrays.toString(nums);
}
A concatenatde-values style
// '1,5,8,98'
public static String arrayToString(int[] nums) {
StringBuilder result = new StringBuilder();
String separator = "";
for (int num : nums) {
result.append(separator).append(num);
separator = ",";
}
return result.toString();
}
Same with brackets
// '[1,5,8,98]'
public static String arrayToString(int[] nums) {
StringBuilder result = new StringBuilder("[");
String separator = "";
for (int num : nums) {
result.append(separator).append(num);
separator = ",";
}
return result.append("]").toString();
}