我有一个程序,它会提示用户输入整数,直到他们键入一个值,以继续程序的下一步。每当用户输入一个整数时,我该如何递增一个名为count的变量呢?顺便说一下,我正在使用count++来增加计数数量,我只是不知道如何在用户输入数据时使其增加。
到目前为止的代码
//variables
int num, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
//loop
do {
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
high = num;
low = num;
//higher or lower
if(count > 0 && num > high)
{
high = num;
}
else if(count > 0 && num < low)
{
low = num;
}
else
{
System.out.println("You did not enter any numbers.");
}
} while (num != -99);
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
发布于 2020-03-29 17:45:33
这很简单。只需将count++
放在while loop
中,如下所示:
// variables
int num, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
// loop
do {
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
count++; // here it goes
high = num;
low = num;
// higher or lower
if(count > 0 && num > high)
{
high = num;
}
else if(count > 0 && num < low)
{
low = num;
}
else
{
System.out.println("You did not enter any numbers.");
}
} while (num != -99);
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
发布于 2020-03-29 17:43:56
您可以将count++;
放在do循环中的任何位置。
发布于 2020-03-29 19:18:54
我理解你为什么要使用它,但是为什么要使用计数器呢?
下面的代码使用一种不同的技术从用户那里获取整数。它还确保提供的数字确实是一个在Integer.MIN_VALUE和Integer.MAX_VALUE范围内的整数:
Scanner userInput = new Scanner(System.in);
String ls = System.lineSeparator();
int high = 0;
int low = Integer.MAX_VALUE;
int num;
String input = "";
while(input.equals("")) {
System.out.print("Enter an integer, (q to quit): --> ");
input = userInput.nextLine().toLowerCase();
if (input.equals("q")) {
if (low == Integer.MAX_VALUE) {
low = 0;
}
break;
}
if (!input.matches("^-?\\d+$")) {
System.err.println("Invalid Entry (" + input + ")! "
+ "You must supply an Integer (int) value!" + ls);
input = "";
continue;
}
boolean invalidInteger = false;
long tmpVal=0;
try {
tmpVal = Long.parseLong(input);
} catch(NumberFormatException ex) {
invalidInteger = true;
}
if (invalidInteger || tmpVal < Integer.MIN_VALUE || tmpVal > Integer.MAX_VALUE) {
System.err.println("Invalid Entry (" + input + ")! " + ls
+ "Number too large (Minimum Allowable: " + Integer.MIN_VALUE
+ " Maximum Allowable: " + Integer.MAX_VALUE + ")!" + ls
+ "You must supply an Integer (int) value!" + ls);
input = "";
continue;
}
num = Integer.parseInt(input);
if (num > high) {
high = num;
}
if (num < low) {
low = num;
}
input = "";
}
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
如果您想要跟踪用户输入了多少条目,那么您仍然可以根据需要应用计数器。
https://stackoverflow.com/questions/60918298
复制