【发布时间】:2015-11-18 02:10:52
【问题描述】:
我正在寻找一种更紧凑的方法来处理我的哨兵循环。我在这里的代码完全按照我的意图工作,但我很好奇是否有一种更简洁或更简洁的方法来做到这一点,而无需任何额外的循环或 if 语句。谢谢!
public void findSmallLarge()
{
//declaring variable
int maxValue = 0;
int minValue = 0;
int input = 0;
boolean done = false;
String sentinel;
//Scanner object
Scanner in = new Scanner(System.in);
//loop asks user to input integers and will tell the user the minimum and maximum values, after the program quits.
System.out.println("Please enter an integer, or press Q to quit");
while (!done && in.hasNextInt())
{
System.out.printf("Please enter an integer, or press Q to quit: ");
input = in.nextInt();
// if input is greater than the maxvalue, update the maxvalue.
if (input > maxValue)
{
maxValue = input;
}
// if input is less than the minimum value, update the minimum value.
if (input < minValue)
{
minValue = input;
}
// if the next input is not an int AND done is false, run the loop until an integer is entered. If q/Q is entered, quit the program.
if (!in.hasNextInt() && !done)
{
while (!in.hasNextInt() && !done)
{
sentinel = in.next();
System.out.print("Please enter a valid integer, or press Q to quit: ");
if (sentinel.charAt(0) == 'Q' || sentinel.charAt(0) == 'q')
{
System.out.println();
System.out.println("You have quit the program");
done = true;
break;
}
}
}
}
// Print the updated min and max values
System.out.println("The Max value is: " + maxValue);
System.out.println("The Minimum value is: " + minValue);
System.out.println();
【问题讨论】: