我想使用我创建的remove方法

时间:2018-06-05 06:47:41

标签: java recursion

//删除方法

public static int[] remove(int[]a){
int [] x = new int[a.length - 1];

for(int i = 1; i <= x.length; i++) {
    x[i-1] = a[i];  
}

return x;}

// IsUniqueMethod检查Passed int的唯一性

public static boolean isUnique(int []x, int n) {
if(x.length == 1) { 
    return true;}
else {

    if(x[0] != n) {
        isUnique(remove(x), n);
    }
    else {
    return false;
    }

}

}

如何更改方法的主体以实现检查唯一性的目标?编译器显示错误,因为即使我已包含return语句,该方法也必须返回boolean值。有人可以解释一下返回方法什么时候不能在我的代码中执行?

1 个答案:

答案 0 :(得分:0)

这永远不会给你正在寻找的isUnique()输出。即使你以某种方式使它超过了ArrayIndexOutOfBound,你编写的代码也是如此低效,以至于每次在递归调用中传递方法参数时都会调用JIT。

试试这个

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

public class Unique {

     private static Scanner sc;

     public static void main(String[] args) {

         sc = new Scanner(System.in);

         //Taking length of the array from the user
         System.out.println("Enter the length of the desired array : ");
         int length = sc.nextInt();

         System.out.println("Please enter the values of the array");
         ArrayList<Integer> al = new ArrayList<Integer>();

         //Entering the values into the arrayList
         for (int i = 0; i < length; i++) {
             al.add(sc.nextInt());
         }

         System.out.println("Enter a number you wish to check : ");
         int checkNumber = sc.nextInt();

         //Using the built-in method indexOf() to check the occurance of the entered number and return its index if present, else returns -1
         System.out.println(al.indexOf(checkNumber)>=0?"The entered number is present in the array":"The entered number is not present in the array");

     }}