I need to return a string type but I keep getting a type mismatch, how do I fix this
public static string[] count(int a, int b) {
int[] arr = a[b + 1 - a];
for(int i = a; i <= b; i++) {
arr[i - a] = i;
}
return arr;
}
public static int[] count(int a, int b) {
int[] arr = new int[a*(b + 1 - a)];
for(int i = a; i <= b; i++) {
arr[i - a] = i;
}
return arr;
}
Or
public static String[] count(int a, int b) {
String[] arr = new String[a*(b + 1 - a)];
for(int i = a; i <= b; i++) {
arr[i - a] = i;
}
return arr;
}
If you want to return a String type but you have an array of int that you need to return, you can use Arrays.toString(int[])
method to convert and format an int[] array into a String. Also your initialization of the int[] arr was wrong, it should be `new int[size].
public static String count(int a, int b) {
int[] arr = new int[b + 1 - a];
for(int i = a; i <= b; i++) {
arr[i - a] = i;
}
return Arrays.toString(arr);
}
Example:
Running the following: System.out.println(count(1,6));
produces:
[1, 2, 3, 4, 5, 6]
Alternatively, you may do an array iteration and format the output as you like using a StringBuffer:
public static String count(int a, int b) {
int[] arr = new int[b + 1 - a];
StringBuffer sb = new StringBuffer();
for(int i = a; i <= b; i++) {
arr[i - a] = i;
}
for (int i=0; i<arr.length; i++){
sb.append(i);
if (i<arr.length-1){
sb.append(" - ");
}
}
return sb.toString();
}
In the above example, each number is separated with - like in
0 - 1 - 2 - 3 - 4 - 5
convert int array to String array and return the string array instead of returning the int array
String strArray[] = Arrays.stream(arr)
.mapToObj(String::valueOf)
.toArray(String[]::new);
System.out.println(Arrays.toString(strArray));
return strArray;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.