ユーザー入力からの変数として数を含め、それは別の変数をインクリメント持っていませんか?

怪獣:

私のプログラムは、それらの入力-99まで(ループ上の)入力整数にユーザーに尋ねます。これは、入力された整数の最高と最低の数字が表示されます。私は増加するたびに、新たな整数でユーザープットは、ユーザによって入力された整数の数を追跡すること、カウントという変数を持っています。どのように私は、-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);
アズハル:

あなたは良いですが近づいていますが、いくつかのポイントを逃しました、

  • あなたがそれらを個別に記述する必要があるため、最大または最小を見つけるためにあなたの条件も間違っています。
  • ユーザが任意の値を入力したかどうか、あなたは、ループの外にこれを決定する必要があります。
  • あなたは第一の入力とハイとローを初期化する必要があります。私はちょうど必要な部分を変更し、あなたのプログラムの中でいくつかの修正をしようとしています。それはあなたを助けることを願っています。

		//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);
}

        

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=371167&siteId=1
おすすめ