java - 'while' 无限循环使用扫描仪输入和 pos/neg 数字
问题描述
我似乎无法理解如何使用 while 循环来确定一个数字是否为正数。虽然(I > 0),如果我输入任何正数,它总是会产生高于 0 的结果,这意味着存在无限循环。
int i = 0;
System.out.println("#1\n Input Validation\n Positive values only"); // #1 Input Validation
System.out.print(" Please enter a value: ");
Scanner scan = new Scanner(System.in);
i = scan.nextInt();
while (i > 0)
{
System.out.println("The value is: " +i);
}
System.out.println("Sorry. Only positive values.");
此外,当我输入负数时,它不会返回扫描仪输入正数。
解决方案
我相信这就是你想要达到的目标。
int i = 0; // int is 0
while (i <= 0) {
// int is 0 or a negative number
System.out.println("#1\n Input Validation\n Positive values only");
System.out.print(" Please enter a value: ");
Scanner scan = new Scanner(System.in);
i = scan.nextInt();
if (i > 0) {
System.out.println("The value is: " + i);
} else {
System.out.println("Sorry. Only positive values.");
}
// if number is positive then continue to termination. If negative then repeat loop
}
密切注意放置 while 循环的位置,因为初始放置肯定会导致无限循环
while (i > 0)
{
System.out.println("The value is: " +i);
// number is positive - repeat loop containing only this line of code to infinity
}
// number is either 0 or negative so continue to termination
推荐阅读
- android - 加载多个位图
- .net - WerFault 系统错误 Visual Studio
- jquery - jQuery $(this) 而不是多个 id
- r - 如何正确更改 R 中 rcpp 中的 ListMatrix 列表
- json - 发送 JSON 内容类型的 POST 请求并在 VB.NET 中显示 JSON 响应
- c# - 从 Core 2 迁移到 Core 2.1 时将 DbContext 作为 DI
- ruby-on-rails - ActiveRecord::StatementInvalid: PG::UndefinedTable: 错误: 与 HABTM 关联与导轨的关系
- c - c中的字符矩阵(动态分配的二维数组)
- laravel - 在 Laravel 5.6 中一次插入父母和孩子
- c# - ASP .NET 4.7 MVC 身份验证和授权标识