简体   繁体   English

如何在遍历多维数组后仅打印一次消息?

[英]How do I print a message only once after iterating through a multidimensional array?

Scanner input = new Scanner(System.in);

int numInput;

int number[][] =  {
  {10, 20, 30}, 
  {15, 25, 35}, 
};

System.out.print("\n\tEnter a Number : ");

// Expected input 10

numInput = input.nextInt();
input.nextLine();

for (int i = 0; i < 2; i++) {
  for (int j = 0; j < 3; j++) {
    if (numInput == number[i][j]) {
      System.out.print("\n\tNumber " + numInput + " Found!");
      System.out.print("\n\tOn line " + i + " Column " +j);
    } else {
      System.out.print("\n\tNumber Not Found!");
    }
  }
}

If the user enters 35, this program will print "Number 35 Found!"如果用户输入 35,该程序将打印“找到 35 号!” for the number found in the array or "Number not Found!"对于在数组中找到的数字或“未找到数字!” for every other element in the array.对于数组中的每个其他元素。

I want it to print this only once.我希望它只打印一次。

It looks like you need to move the print statement for "Number not Found" outside of your for loops.看起来您需要将“未找到数字”的打印语句移到 for 循环之外。 Like this:像这样:

Scanner input = new Scanner(System.in);

    int numInput;

    int number[][] =  { {10, 20, 30}, 
                        {15, 25, 35}, 
                    };

System.out.print("\n\tEnter a Number : ");

//Expected input 10

numInput = input.nextInt();
input.nextLine();

boolean found = false;

for (int i = 0; i < 2; i++) {

    for (int j = 0; j < 3; j++) {

        if (numInput == number[i][j]) {

            found = true;
            System.out.print("\n\tNumber " + numInput + " Found!");
            System.out.print("\n\tOn line " + i + " Column " +j);
        }
    }
}

if (!found) {
    System.out.print("\n\tNumber Not Found!");
}

The way you have it now, it is always going to either print Found or Not Found, for every item.按照您现在的方式,它总是会为每个项目打印“找到”或“未找到”。 But if you only want it to print once at the end, you'll need to have some sort of flag to determine if it was found, and if not, then print.但是如果你只希望它在最后打印一次,你需要有某种标志来确定它是否被找到,如果没有,则打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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