带有用户输入的 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
运行代码这里。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。