我有一个问题要求用户输入两个数字。然后,您必须在这两个数字之间打印偶数...如果第一个数字小于第二个数字,则偶数将从小到大打印。如果第一个数字较大,则它们从最大到最小打印。我很困惑,我的代码显示......
import java.util.Scanner;
public class Lab605{ //create for loops to find given output.
public static void main(String[] args){
int num1, num2;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type a number: ");
num1 = keyboard.nextInt();
System.out.print("Enter another number: ");
num2 = keyboard.nextInt();
int i = 0;
while ( i <= num1){
if(num1 < num2){
if(i%2 == 0){
System.out.print("The even numbers between " + num1 + " and " + num2+ " are: " + i);
i++;
}
}
}
}
}
有人可以帮助指导我如何正确地执行此操作吗?还需要使用while循环!
答案 0 :(得分:0)
试试这个:
public static void main(String[] args) {
int num1, num2;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type a number: ");
num1 = keyboard.nextInt();
System.out.print("Enter another number: ");
num2 = keyboard.nextInt();
int i = 0;
int l, s;
boolean upToDown = false;
if (num1 > num2) {
l = num1;
s = num2;
upToDown = true;
} else {
l = num2;
s = num1;
}
if (upToDown) {
i = l % 2 == 0 ? l : l - 1;
while (i - s > 0) {
System.out.println(i - 2);
i = i - 2;
}
} else {
i = s % 2 == 0 ? s : s + 1;
while (l - i > 0) {
System.out.println(i + 2);
i = i + 2;
}
}
}
答案 1 :(得分:0)
检查下面的代码,我添加了评论。我想你可以理解,
import java.util.Scanner;
public class Lab605 { // create for loops to find given output.
public static void main(String[] args) {
int num1, num2;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type a number: ");
num1 = keyboard.nextInt();
System.out.print("Enter another number: ");
num2 = keyboard.nextInt();
int smallNum = 0; // Identify small number
int largeNum = 0; // Identify large number
boolean isNum1Large = false;
if (num1 - num2 > 0) {
smallNum = num2;
largeNum = num1;
isNum1Large = true;
} else {
smallNum = num1;
largeNum = num2;
}
if (isNum1Large) { //If first number is large
for (int i = largeNum - 1; i > smallNum; i--) {
if (i % 2 == 0) {
System.out.println(i);
}
}
} else { //If first number is small
for (int i = smallNum + 1; i < largeNum; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
}
}