为什么这个程序告诉我的比我想知道的更多?我希望它只告诉我一次它找到了号码或没有



为什么这个程序告诉我的比我想知道的更多?("未找到"、"未找到"等)我希望它只告诉我一次它找到了号码或没有。我相信这与最后一个循环有关。有人告诉我://你需要在这里循环,范围从 0 到 numNum,在这个 Num[i] 中搜索数字(最后一个循环)。

// HighLow Program
public class numSearch2 //Program
{ // here is the main method of the program
    public static void main(String[] args) {
        int i, numNums, outPut; //variables
        System.out.println("This program will allow you to enter some numbers.nIt will then tell you the numbers you entered. nThen you will be asked to enter any number and nthe program will tell you where in the array the number is located. ");
        System.out.println("nFirst, please enter how many numbers you will enter: "); //input the number of numbers
        numNums = InputUtils.GetInt(); //pulls from InputUtils program
        if (numNums > 0) //if statement
        {
            // dynamically declare (or 'new up') the array of int...
            int numArray[]; // variable
            numArray = new int[numNums];
            //loop x times
            for (i = 0; i < numNums; i++) {
                System.out.println("Please enter number " + i + ": "); // enter this number
                numArray[i] = InputUtils.GetInt();//pulls from InputUtils program
            }   // end if statement
            System.out.println("Here are the numbers you entered: "); //shows all the numbers entered
            for (i = 0; i < numNums; i++) {
                System.out.println("n Number " + i + " is " + numArray[i]); //spits out numbers
            }
            System.out.println("nWhat number would you like to search for: "); //find the number
            outPut = InputUtils.GetInt(); //pulls from InputUtils program
            for (i = 0; i < numNums; i++)//loop for the return numbers
                if (numArray[i] == outPut) //if the number you're looking for matches up with a number entered, this will tell you
                {
                    System.out.println("That number was found at location " + i); //tells you what number it matches with
                } else //if the number you're looking for doesn't match up:
                {
                    System.out.println("number not found"); //tells the user the number cannot be found
                }
        } else {
            System.out.println("Goodbye!");
        }

    }  // end main
}   // end class

内部循环替换为:

boolean found = false;
for (i=0; i<numNums; i++)
    if (numArray[i]==outPut) {
        System.out.println("That number was found at location " +i );
        found = true;
    }
}
if (!found) {
    System.out.println("number not found");
}

您必须记住您是否发现了任何值,并且只有在整个迭代打印之后,如果是这种情况,您才没有找到任何东西。

最新更新