简体   繁体   English

如何在for循环中打印单个输出?

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

How can I print only one output in for loop?如何在for循环中只打印一个输出? If the number is in array then it will print "Present" but if the number is not in the array it will print "Nope" .如果数字在数组中,那么它将打印"Present"但如果数字不在数组中,它将打印"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预期产出: 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:添加了 Java 8 解决方案:

If you are using Java 8 or above you can use Stream also to replace above for loop.如果您使用的是 Java 8 或更高版本,您也可以使用 Stream 来替换上面的 for 循环。 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您所需要的只是将 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