It will terminate because the loop checking for the test number will run at least once, and at most n times (n being the number of elements in the array).
It should always return the correct answer, using logical situations to test it. For example, if the test number was 6, and the first number in the list also happened to be 6, then the loop would run once, comparing the two numbers, and set the variable to true to indicate that the test number is actually in the list, and return the related statement. If the test number happened to be the second element in the array, the loop would run twice and then set the variable to true. If the test number is not in the array, it would check every number in the list before returning false.
(Note: I included the break so that the loop would not have to continue checking the rest of the array if the test number was already found in the list before)
import java.util.Scanner;
public class FindANumber
{
public static void main(String[] args)
{
boolean inList = false;
int i = 0;
int testNumber;
Scanner scan = new Scanner(System.in);
System.out.print("How many numbers are in the list? ");
int numberOfItems = scan.nextInt();
int[] list = new int[numberOfItems];
int numbersInput = numberOfItems;
while(numberOfItems > 0)
{
System.out.println("Enter a number into the list.");
int aNumber = scan.nextInt();
list[i] = aNumber;
i++;
numberOfItems--;
}
System.out.println("What is the number you want to test? ");
testNumber = scan.nextInt();
//Will go through each element in the array and compare to the test input. if it matches any element, it will set
//inList to be true and break from the loop so that we do not have to check the rest of the numbers.
for(int j = 0; j < numbersInput; j++)
{
if(list[j]==testNumber)
{
inList = true;
break;
}
}
if(inList == true)
{
System.out.println(testNumber + " is in the list!");
}
else
{
System.out.println(testNumber + " is NOT in the list.");
}
}
}
perfect.
ReplyDelete