3 回答
TA贡献1811条经验 获得超5个赞
只需再添加一个if以检查这是否是第一次迭代:
public static void isevennumber(int startwith, int endwith) {
for (int i = startwith; i <= endwith; i++) {
if (i % 2 == 0)
System.out.println("you have entered an even number which is " + i);
else if (i == startwith)
System.out.println("you haven't entered an even number");
}
}
TA贡献1906条经验 获得超10个赞
这里的问题是,每次在循环中数字不是奇数时,它都会打印出您没有输入偶数。
你可以这样试试:
public static void main(String[] args) {
isevennumber(1, 5);
}
public static void isevennumber(int startwith, int endwith) {
List<Integer> evenNumbers = new ArrayList();
for (int i = startwith; i <= endwith; i++) {
if (i % 2 == 0) {
evenNumbers.add(i);
}
}
if (evenNumbers.isEmpty()) {
System.out.println("you haven't entered an even number");
return;
}
System.out.println("you have entered the following even numbers " + evenNumbers);
}
这将打印出:
you have entered the following even numbers [2, 4]
TA贡献1859条经验 获得超6个赞
您错过了一个步骤,这里的问题是每次循环中数字不是奇数时,它都会打印您没有输入偶数。
以下是适合您的正确解决方案。
public static void isevennumber(int startwith, int endwith) {
for (int i = startwith; i <= endwith; i++)
{
if (i % 2 == 0)
{
System.out.println("you have entered an even number which is " + i);
}
else if (i == startwith)
{
System.out.println("you haven't entered an even number");
}
}
}
添加回答
举报