我正在我的一门大学课程中研究一个简单的JAVA问题。我为这个程序感到困惑。我将显示到目前为止的内容,并提出我必须回答的问题。我还在StackOverflow上看过类似的问题,但问题不一样,所以对我们没有帮助。我需要编写的程序是:

编写一个使用“ while”循环执行以下步骤的程序:

a。)提示用户输入两个整数:“ firstNum”和“ secondNum”(firstNum必须小于secondNum)

b。)输出介于“ firstNum”和“ secondNum”之间的所有奇数。

c。)输出“ firstNum”和“ secondNum”之间的所有偶数之和。

这就是我到目前为止所拥有的...(我仍然需要计算偶数并将它们相加)

//import classes
import java.util.*;

public class chapter5no9
{
    static Scanner console = new Scanner(System.in);

    public static void main(String[] args)
    {

    //Part A
    int firstNum;
    int secondNum;
    int sumEven;

    System.out.println("Please enter an integer: ");
    firstNum = console.nextInt();

    System.out.println("Please enter another integer less than the first integer: ");
    secondNum = console.nextInt();

    //Part B
    if (firstNum < secondNum)
    {
        System.out.print("Your second number is greater than the first.  So Please re-enter: ");
        secondNum = console.nextInt();
    }
    else
    {
        System.out.print("Odd Numbers: ");
        firstNum++;
        while (firstNum > secondNum)
        {
            if (secondNum % 2 != 0)
            {
                System.out.print(" " + secondNum);
            }
            secondNum++;
        }

        System.out.println();
        System.out.print("Sum of Even Numbers: ");
        firstNum++;
        while (firstNum > secondNum)
        {
            if (secondNum % 2 != 0)
            {
                System.out.print(" " + secondNum);
            }
            secondNum++;
        }
    }
}


}

最佳答案

我创建了loopCounter变量来处理所需的迭代,而无需更改用户输入的值。对您的代码进行了以下更改。

A部分:添加了while循环以验证用户输入。还更改了if语句中的逻辑。

B部分:使用一个循环打印奇数和总偶数

   //Part A
   int firstNum;
   int secondNum;
   int sumEven=0;

   System.out.println("Please enter an integer: ");
   firstNum = input.nextInt();

   System.out.println("Please enter another integer less than the first integer: ");
   secondNum = input.nextInt();

   //Part B

   //validate input in a loop
   while(true)
   {
     if (firstNum > secondNum)
     {
         System.out.print("Your second number is larger than the first.  So Please re-enter: ");
         secondNum = input.nextInt();
     }
     else
     {
         break;
     }
   }

       System.out.print("Odd Numbers: ");
       int loopCounter=firstNum;
       while(loopCounter<secondNum)
       {
         if (loopCounter%2!=0)
         {
             System.out.print(" " + loopCounter);
         }//end if
         else
         {
             sumEven+=loopCounter;
         }//end else
         loopCounter++;
       }

       System.out.println();
       System.out.print("Sum of Even Numbers: ");
       System.out.print(sumEven);

   }

关于java - 输出两个整数之间的偶数和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33313482/

10-12 02:43