为什么这个程序告诉我的不仅仅是我想知道的? (“未找到,”未找到,“等等)我希望它只告诉我一旦它找到了数字或没有。我相信它与最后一个循环有关。我被告知://你需要在这里循环,范围从0到numNum,在thisNum [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
答案 0 :(得分:0)
用以下内容替换内循环:
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");
}
你必须记住你是否发现了任何价值,并且只有在整个迭代打印之后你没有找到任何东西,如果是这样的话。