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

9nvpjoqh  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(434)

如何在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

nfg76nw0

nfg76nw01#

您需要在循环外维护一个变量,并使用该变量在循环外打印,如下所示:

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解决方案:
如果您使用的是java8或更高版本,那么还可以使用stream来替换上面的for循环。具体如下:

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

uidvcgyl2#

你在正确的轨道上。你只需要在条件语句中添加其他内容

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

相关问题