簡體   English   中英

如何在for循環中打印單個輸出?

[英]how to print a single output in for loop?

如何在for循環中只打印一個輸出? 如果數字在數組中,那么它將打印"Present"但如果數字不在數組中,它將打印"Nope" 我需要搜索用戶輸入的數字。

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

}

輸入

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

輸出

Nope
Nope
Present
Nope
Nope

預期產出: Present

您需要在循環外維護一個變量並使用該變量在循環外打印,如下所示:

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

添加了 Java 8 解決方案:

如果您使用的是 Java 8 或更高版本,您也可以使用 Stream 來替換上面的 for 循環。 如下 :

final boolean isMatched = Arrays.stream(num).anyMatch(a -> a == searchNum);

你走在正確的軌道上。 您所需要的只是將 else 添加到您的條件語句中

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM