如果为零,则不要使用方法

do not use method if zero in

我需要帮助弄清楚如何在方法出现时不调用方法 firstPosition return 零。

import java.util.Scanner;

public class SearchArray 
{
    public static void main(String[] args)
    {
        int[] numbers = {1,2,3,4,5,6,7,8,9,10,2,4,6,8,10,1,3,5,7,9};
        int searchValues;
        int value;
        int position;

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter a number between 1 and 10: ");
        searchValues = keyboard.nextInt();

        value = occurs(searchValues, numbers);
        position = firstPosition(searchValues, numbers);


        System.out.println(searchValues + " occurs " + value + " times, the           first occurence" + " is at position " + (position + 1));


    }
    public static int occurs (int searhValue, int[] numbers)
    {
        int searchValues = 0; 

        for (int i = 0; i<numbers.length; i++)
        {
            if(searhValue == numbers[i])
            searchValues++; 
        }
        return searchValues;
    }
    public static int firstPosition (int searchValue, int[] numbers)
    {
        int i;

        for (i=0; i<numbers.length; i++)
        {
            if(searchValue == numbers[i])
            return i;       
        }
        return -1;
    }

}

//我很确定这是我遗漏的简单事情,但我似乎无法//弄明白。 //任何帮助将不胜感激!

提前致谢。

为了防止在没有元素匹配输入值时调用firstPosition,你必须在调用occurs后检查它:

    value = occurs(searchValues, numbers);
    System.out.println(searchValues + " occurs " + value + " time(s)");
    if (value > 0) {
        position = firstPosition(searchValues, numbers);

        System.out.println("The first occurence" + " is at position " + (position + 1));
    }