不包括一个数字作为用户输入的变量并让它递增另一个变量?

Not including a number as a variable from user input and having it increment another variable?

我的程序要求用户输入整数(循环),直到他们输入 -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);
}

        

我会推荐以下解决方案:

首先,在循环之前从用户那里得到一个数字。

然后检查数字是否为-99。

如果是,你知道该怎么做。

如果没有,启动一个 do-while 循环并执行以下操作:

  1. 增加计数。

  2. 更新您的最低价和最高价。

  3. 而循环体的最后一条语句会从用户那里得到另一个数字。

循环体后的 while 条件将检查输入的最新数字不是 -99。