带有用户输入的 Java while 循环

Sheeraz Gul 2024年2月16日
带有用户输入的 Java while 循环

有时,在使用循环时,我们在循环运行期间需要多个用户输入。本教程演示了如何在 Java 中创建一个不断请求用户输入的 while 循环。

在 Java 中使用带有用户输入的 while 循环

我们将使用用户输入创建一个 while 循环。此示例将检查数组中是否存在数字。

循环将继续接受用户输入,直到输入数字不是数组的成员。

代码:

import java.util.*;
import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] input_array = {10, 12, 14, 17, 19, 21};
    System.out.println(Arrays.toString(input_array));
    System.out.println("Enter number to check if it is a member of the array");
    while (true) {
      Scanner input_number = new Scanner(System.in);
      int number = input_number.nextInt();
      if (Arrays.stream(input_array).anyMatch(i -> i == number)) {
        System.out.println(number + " is the member of given array");
      } else {
        System.out.println(number + " is not the member of given array");
        System.out.println("The While Loop Breaks Here");
        break;
      }
    }
  }
}

让我们尝试多个输入,直到循环中断。当输入一个不是数组成员的数字时,循环将中断。

输出:

[10, 12, 14, 17, 19, 21]
Enter number to check if it is a member of the array
10
10 is the member of given array
12
12 is the member of given array
13
13 is not the member of given array
The While Loop Breaks Here

运行代码这里

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相关文章 - Java Loop