首页 > 解决方案 > 不包括来自用户输入的数字作为变量并让它增加另一个变量?

问题描述

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

标签: javaloopsvariablesincrement

解决方案


你的方法很好,但你错过了一些点,

  • 您找到 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);
}

        


推荐阅读