当前位置: 首页 > 知识库问答 >
问题:

不兼容的类型:java.lang.String不能转换为int[]

卜勇
2023-03-14
public static int[] getAllEvens(int[] array)
    {  
        String evens;

        for(int i=0; i<array.length; i++)
        {
            if(array[i]%2==0)
            {
                 evens = (array[i]+" ");
            }
        }
        return evens;   
    }

共有1个答案

万俟招
2023-03-14

编辑1:使用扫描程序&使用临时ArrayList使int[]紧凑

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        int[] evens = getAllEvens1(arr);
        for (int i : evens) {
            System.out.print(i + " ");
        }
    }

    public static int[] getAllEvens1(int[] array) {
        int[] temp = new int[array.length]; // if all of array are `even`..
        Arrays.fill(temp, -1); //or any flag.. to indicate it's unnecessary

        int j = 0;
        for (int i : array) {
            if (i % 2 == 0) {
                temp[j++] = i;
            }
        }

        int[] ret = new int[j];
        j = 0;
        for (int i : temp) {
            if (i != -1) {
                ret[j++] = i;
            }
        }
        return ret;

    }

    public static int[] getAllEvens(int[] array) {
        ArrayList<Integer> temp = new ArrayList();

        for (int i : array) {
            if (i % 2 == 0) {
                temp.add(i);
            }
        }
        return temp.stream().mapToInt(Integer::intValue).toArray();
    }
}

你的代码中有几个问题。首先,您试图返回字符串,而您的函数返回类型是int[];其次,您只为尚未初始化的字符串分配当前偶数。

修复:

 public static String getAllEvens(int[] array) {
        StringBuilder evens = new StringBuilder();

        for (int i = 0; i < array.length; i++) {
            if (array[i] % 2 == 0) {
                evens.append(array[i]).append(" ");
            }
        }
        return evens.toString();
    }
  public static String getAllEvens(int[] array) {
        String ret = "";

        for (int i = 0; i < array.length; i++) {
            if (array[i] % 2 == 0) {
                ret += array[i] + " ";
            }
        }
        return ret;
    }
 类似资料: