我的程序要求个人输入2个数字(即10和20)。 我希望输出为:
偶数:10 12 14 16 18 20
我的代码:
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);
}
答案 0 :(得分:1)
您接近您所追求的结果,只需要重新排列几行的顺序并添加一个if
支票。
我已经制作了一个完整的示例,按预期运行并允许奇数和偶数。您可以使用以下代码替换代码:
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();
}