如何在Java中将输入值增加2

时间:2022-06-29 09:06:23

My program asks the individual to input 2 numbers (ie; 10 and 20). I would like the output to be:

我的程序要求个人输入2个数字(即10和20)。我希望输出为:

Even numbers: 10 12 14 16 18 20

偶数:10 12 14 16 18 20

My code:

  System.out.println("Enter an integer:");
  int firstNum = keyboard.nextInt();

  System.out.println("Enter another integer larger than the first one:");
  int secondNum = keyboard.nextInt();

  System.out.println();

  int mod = firstNum % 2;

  while ((firstNum < secondNum) && mod == 0)
  {
      firstNum = firstNum + 2;
      System.out.print("Even numbers" +firstNum);
  }

1 个解决方案

#1


1  

You are close to the result you are after, just need to rearrange the order of a couple of lines and add one if check.

你接近你想要的结果,只需要重新排列几行的顺序,如果检查就添加一行。

I have made a complete example that runs as expected and allows for both odd and even numbers. You can replace your code with the following:

我做了一个完整的例子,按预期运行,允许奇数和偶数。您可以使用以下代码替换您的代码:

public static void main(String[] args)
{
    Scanner keyboard = new Scanner(System.in);      
    System.out.println("Enter an integer:");
    int firstNum = keyboard.nextInt();

    System.out.println("Enter another integer larger than the first one:");
    int secondNum = keyboard.nextInt();

    System.out.println();

    int mod = firstNum % 2;
    //If first number is odd, increase by one to make it even.
    if (mod != 0)
    {
        firstNum++;
    }

    System.out.print("Even Numbers: ");
    while (firstNum <= secondNum)
    {
        System.out.print(firstNum + " ");
        firstNum = firstNum + 2;
    }
    keyboard.close();
}

#1


1  

You are close to the result you are after, just need to rearrange the order of a couple of lines and add one if check.

你接近你想要的结果,只需要重新排列几行的顺序,如果检查就添加一行。

I have made a complete example that runs as expected and allows for both odd and even numbers. You can replace your code with the following:

我做了一个完整的例子,按预期运行,允许奇数和偶数。您可以使用以下代码替换您的代码:

public static void main(String[] args)
{
    Scanner keyboard = new Scanner(System.in);      
    System.out.println("Enter an integer:");
    int firstNum = keyboard.nextInt();

    System.out.println("Enter another integer larger than the first one:");
    int secondNum = keyboard.nextInt();

    System.out.println();

    int mod = firstNum % 2;
    //If first number is odd, increase by one to make it even.
    if (mod != 0)
    {
        firstNum++;
    }

    System.out.print("Even Numbers: ");
    while (firstNum <= secondNum)
    {
        System.out.print(firstNum + " ");
        firstNum = firstNum + 2;
    }
    keyboard.close();
}