java - 不包括来自用户输入的数字作为变量并让它增加另一个变量?
问题描述
我的程序要求用户输入整数(在循环中),直到他们输入 -99;然后将显示输入整数的最高和最低数字。我有一个名为 count 的变量,每次用户输入一个新整数时它都会递增,以跟踪用户输入的整数个数。我怎样才能不将 -99 作为整数之一包含在内并且不增加计数?
代码:
//variables
int num = 0, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
low = num;
high = num;
//loop
while(num != -99){
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
count++;
if (num == -99 && count == 0)
{
count--;
System.out.println("You did not enter a number");
} //outer if end
else {
//higher or lower
if(count > 0 && num > high)
{
high = num;
} //inner else end
else if(count > 0 && num < low)
{
low = num;
} //inner else if end
else
{
} //inner else end
} //outer else end
}
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
解决方案
你的方法很好,但你错过了一些点,
- 您找到 max 或 min 的条件也是错误的,因为您必须单独编写它们。
- 用户是否输入任何值,您必须在循环之外决定。
- 您必须使用第一个输入初始化高和低。我正在尝试对您的程序进行一些更正,只是更改所需的部分。希望它会帮助你。
//variables
int num = 0, count = 0, high =0 , low = 0;
Scanner userInput = new Scanner(System.in);
//loop
while(true){
//Using infinite loop, we will break this as per condition.
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
if(num == -99)
{
break;
}
count++;
if(count == 1)
{//initialize high and low by first number then update
high = num;
low = num;
}
//to check highest
if(num > high)
{
high = num;
}
//to check smallest
if(num < low)
{
low = num;
}
}
if (count == 0)
{//Here we check that if user enter any number or directly entered -99
System.out.println("You did not enter a number");
}
else
{
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
}
推荐阅读
- bash - 无法在 macOS Catalina 10.15 上通过 mktemp 转换为临时文件
- firebase - 当我尝试显示当前 Firebase 用户的电子邮件时,为什么会得到 null?
- mongoose - 仅在超测的一项测试中连接 ECONNREFUSED 127.0.0.1:80 错误
- flutter - 如何使非固定大小的父行/列填满整个空间
- java - Javadoc 未生成 -- doc 文件夹
- php - 如何在 PHP 中用未组织的数组元素组织 CSV 数据?
- ios - 无法让我的“保存”按钮工作,我的按钮在按下时什么也不做
- amazon-web-services - 用于 ECS 服务更新的 CloudWatch 事件规则和 SNS
- django-rest-framework - 序列化器的更新方法只创建不更新(Django rest框架)
- azure - Azure B2C 自定义策略 - api.localaccountsignup - 只有部分字段会自动翻译