仅使用while循环我需要一个程序读取2个整数n,m(n <= m)并打印n和m之间的所有偶数(包括)。例如,如果输入值为2和9,则输出必须是2 4 6 8.或者对于输入3和12,程序必须产生4 6 8 10 12。
这是我想象的,但它不起作用!
请帮助!!!!
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer value-> ");
int k = input.nextInt();
input = new Scanner(System.in);
System.out.print("Enter a larger value-> ");
int j = input.nextInt();
int i = 1;
while (i >= k) {
System.out.println(i);
i = i + 2;
System.out.println(i);
if (i < j) {
i = i + 2;
System.out.println(i);
}
}
答案 0 :(得分:3)
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer value-> ");
int k = input.nextInt();
input = new Scanner(System.in);
System.out.print("Enter a larger value-> ");
int j = input.nextInt();
int i = k;
if(i % 2 == 1)
i++;
while (i <= j) {
System.out.println(i);
i = i + 2;
}
答案 1 :(得分:2)
试试这个,我修改了int i = k
,而循环条件i < = j
&amp;为偶数增加了逻辑
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer value-> ");
int k = input.nextInt();
input = new Scanner(System.in);
System.out.print("Enter a larger value-> ");
int j = input.nextInt();
int i = k;
while (i <= j) {
if (i%2 == 0) {
System.out.println(i);
}
i++;
}
答案 2 :(得分:2)
我是用for
做的,但也许我已经晚了lol
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer value-> ");
int k = input.nextInt();
System.out.print("Enter a larger value-> ");
int j = input.nextInt();
for (int i=k;i<=j; i++){
if (i%2 == 0){
System.out.println(i);
}
}
答案 3 :(得分:1)
这是我的解决方案,有一些帮助,所以你可以学习
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer value-> ");
int k = input.nextInt();
// >> input = new Scanner(System.in); do not need this line
System.out.print("Enter a larger value-> ");
int j = input.nextInt();
// int i = 1; you do not need extra value you can reuse k
if ( k % 2 != 0){ // number is odd
++k
}
while(k < j) {
System.out.println("" + k);
k += 2;
}