简体   繁体   中英

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

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);

You are on the right track. All you need is to add else to your conditional statement

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM