Java程序。如何通过数组循环我的" isLucky方法?以及如何在main方法中打印结果?

时间:2014-04-04 01:40:12

标签: java arrays loops

如何在main方法中打印结果?我如何将“isLucky”方法循环到数组?我之前发布过一段时间,并被告知我应该再次发布更少的问题。

import java.util.Scanner;

public class FunArrays {

public static void main(String[] args) {

    luckyNumber1 = 7;
    luckyNumber2 = 13;
    luckyNumber3 = 18;


    int[] a=new int[10];
    Scanner sc=new Scanner(System.in);
        System.out.println("Please enter numbers...");
        for(int j = 0; j < a.length; j++)
        a[j] = sc.nextInt();

    boolean b = isLucky(a);

        int result; 

        if(b){
            result = sum(a);
        }

        else{
            result = sumOfEvens(a);
        }

}

public static int sum(int [ ] value)  
{
      int i, total = 0;
      for(i=0; i<10; i++)
      {
          total = total + value[ i ];
      }

      return (total);
}
static int sumOfEvens(int array[]) 
{
int sum = 0;
for(int i = 0; i < array.length; i++) {
    if(array[i] % 2 == 0)
        sum += array[i];
}
return sum;
}
public static boolean isLucky (int[] array) 
{

    if ( array[i] == 7 || array[i] == 13 || array[i] == 18 )
        return true; 

    else
        return false;
}

// write the static methods isLucky, sum, and sumOfEvens

}

1 个答案:

答案 0 :(得分:1)

试试这个,

public static boolean isLucky(int[] array)
    {
        for (int i = 0; i < array.length; i++)
        {
            if (array[i] == 7 || array[i] == 13 || array[i] == 18)
            {
                System.out.println("Going to return true");
                return true;
            }
        }
        return false;
    }

在主要方法中使用System.out.println("Result : "+result);打印结果