如何调用功能

时间:2014-01-04 13:49:04

标签: java

我是java的新手。 我需要编写一个获取数组A的函数(数组大小为n),并且仅在以下情况下返回true:

 A[x]>A[y]-10 (While 0≤x<n 0≤y<n  x≠y)

例如,此数组返回true:A={1, 2, 5, 7, 9, 3}

好的,这是我的代码,我正在尝试调用函数“checkIfLargebyTen”,但它不起作用。怎么了? 先谢谢!

    package Ass2;

    public class Part0 {

            public static boolean forAllExists(int[] A) {
            boolean ans = true;
                for(int i=0; i<A.length; i++)
                {
                    if(checkIfLargebyTen(A,i)==false)
                    {
                        ans=false;
                    }//if
                }//for


//Boolean function that check if  A[x]>A[y]-10
           boolean checkIfLargebyTen(int[] arr, int x) {
              boolean ans=false;
                  for(int y=0; y<arr.length && ans==false; y++)
                   {
                    if (x!=y && arr[x]>arr[y]-10)
                    {
                        ans=true;
                    }//if
                }//for
                return ans;
            }//CheckFunction
                return ans;
            }//AllExixstsFunction
    }//class

2 个答案:

答案 0 :(得分:0)

在Java中,您无法在方法中定义方法。你应该关闭'forAllExists method before declaring the checkIfLargeByTen`:

public class Part0 {

        public static boolean forAllExists(int[] A) {
            boolean ans = true;
            for(int i=0; i<A.length; i++)
            {
                if(checkIfLargebyTen(A,i)==false)
                {
                    ans=false;
                }//if
            }//for

            return ans; // return missing in the OP
        } // close forAllExists - missing in the OP

       //Boolean function that check if  A[x]>A[y]-10
       static boolean checkIfLargebyTen(int[] arr, int x) {
          boolean ans=false;
              for(int y=0; y<arr.length && ans==false; y++)
               {
                if (x!=y && arr[x]>arr[y]-10)
                {
                    ans=true;
                }//if
            }//for
            return ans;
        }//CheckFunction
}//class

答案 1 :(得分:0)

我猜你可以使用两个for循环来创建遍历所有值的函数,并且只要一对(x,y)不符合你的条件,就返回false。我认为你做的是同样的事情,但这只是一种方法。

public static boolean checkSomething(int[] arr)
{
   for(int i = 0;i < arr.length;i ++)
   {
      for(int j = 0;j < arr.length;j ++)
      {
         if(arr[i]<=arr[j]-10) return false;
      }
   }

   return true;
}

杰西。