我正在编写一个程序作为我学习Java的培训,可以查看用户输入的任何数字之间的偶数和奇数,这个问题是,如果我在开始时输入偶数,它将显示消息< / p>
您没有输入偶数
如果用户在开始时输入了奇数,我只希望他首先查看此消息
def prev(x):
return x.__prev__()
class infinity_functional:
def __init__(self):
self.n=0
def __next__(self):
Next = infinity_functional()
Next.n = self.n + 1
return Next
def __prev__(self):
Prev = infinity_functional()
Prev.n = self.n - 1
return Prev
def __repr__(self):
return str(self.n)
enter code here
>>>x=infinity_functional()
>>>x
0
>>> next(next(next(x)))
3
>>> y=next(next(next(x)))
>>> prev(y)
2
输出为
public static void main(String[] args) {
isevennumber(1, 5);
}
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 {
System.out.println("you haven't entered an even number");
}
}
}
对不起,有任何错误,这是我在这里的第一篇文章
答案 0 :(得分:2)
这里的问题是,每次循环中数字都不是奇数时,它将打印您没有输入偶数的数字。
您可以尝试这样:
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]
答案 1 :(得分:1)
只需再添加一个author_id
来检查这是否是第一次迭代:
if
答案 2 :(得分:-1)
您错过了一个步骤,这里的问题是每次循环中的数字不是奇数时,它都会打印出您没有输入偶数。
以下是适合您的正确解决方案。
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");
}
}
}