繁体   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