Skip to content
Advertisement

how to print a single output in for loop?

How can I print only one output in for loop? If the number is in array then it will print "Present" but if the number is not in the array it will print "Nope". And I need to search the number the user inputed.

Scanner in = new Scanner(System.in);

int numOfLoop = in.nextInt(); // How many loop I want.
int[] num = new int[numOfLoop];// Array of the numbers.

for (int i = 0; i < numOfLoop; i++)// getting the numbers.
{

    num[i] = in.nextInt();

}

int searchNum = in.nextInt();// The number that is to be search.

for (int i = 0; i < numOfLoop; i++)// For loop to search the number in the array.
{

    if (num[i] == searchNum) {
        System.out.println("Present");
    }
    if (searchNum != num[i]) {
        System.out.println("Nope");
    }

}

Input:

5 //How many iteration I want
3 21 2 5 23 //Input 5 Number
2 //Number to be searched

output:

Nope
Nope
Present
Nope
Nope

Expected Output: Present

Advertisement

Answer

You need to maintain a variable outside the loop and print outside the loop using that variable as below:

boolean isMatched = false;

for(int i = 0; i <numOfLoop; i++)//For loop to search the number in the array.
  {

   if(num[i] == searchNum) {
    isMatched = true;
    break;
   }
  }

if(isMatched) {
   System.out.println("Present");
} else {
   System.out.println("Nope");
}

Added Java 8 Solution:

If you are using Java 8 or above you can use Stream also to replace above for loop. As below :

final boolean isMatched = Arrays.stream(num).anyMatch(a -> a == searchNum);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement