Java:执行while循环,偶数,然后重试
我可以简单地循环,但我很难只做偶数和奇数。我希望它像这样,例如: 输入您的号码:20 2 4 6 8 10 12 14 18 20 你想再做一次吗?是/否 我的代码:Java:执行while循环,偶数,然后重试,java,loops,while-loop,do-while,Java,Loops,While Loop,Do While,我可以简单地循环,但我很难只做偶数和奇数。我希望它像这样,例如: 输入您的号码:20 2 4 6 8 10 12 14 18 20 你想再做一次吗?是/否 我的代码: public static void main(String[] args) { Scanner input=new Scanner(System.in); String c = null; do { int i; System.out.println("Enter
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String c = null;
do {
int i;
System.out.println("Enter a Number:");
int n = input.nextInt();
for(i=1; i<n; i++) {
System.out.println(i);
if(n%2==0) {
System.out.println(i + " " );
}
System.out.println("Try Again? Y/N");
c = input.next();
}
}while(c.equalsIgnoreCase("y"));
}
publicstaticvoidmain(字符串[]args){
扫描仪输入=新扫描仪(System.in);
字符串c=null;
做{
int i;
System.out.println(“输入一个数字:”);
int n=input.nextInt();
对于(i=1;i您的代码在说如果(n%2==0)
但是循环在i
上迭代。这个n
在每个循环中都不会改变
这可能不是代码中的唯一问题,但您肯定应该看看i
在循环中做了什么,而不是那一行的n
。如果(n%2==0)
,您的代码会说,但循环会在i
上迭代。这n
在每个循环中都不会改变
这可能不是代码中的唯一问题,但您肯定应该查看i
在循环中的作用,而不是该行上的n
。您需要检查i%2==0
而不是n%2==0
演示:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String c = null;
do {
System.out.print("Enter a Number: ");
int n = input.nextInt();
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
System.out.print("\nTry Again? Y/N: ");
c = input.next();
} while (c.equalsIgnoreCase("y"));
}
}
Enter a Number: 20
2 4 6 8 10 12 14 16 18 20
Try Again? Y/N: y
Enter a Number: 25
2 4 6 8 10 12 14 16 18 20 22 24
Try Again? Y/N: n
您需要检查i%2==0
而不是n%2==0
演示:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String c = null;
do {
System.out.print("Enter a Number: ");
int n = input.nextInt();
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
System.out.print("\nTry Again? Y/N: ");
c = input.next();
} while (c.equalsIgnoreCase("y"));
}
}
Enter a Number: 20
2 4 6 8 10 12 14 16 18 20
Try Again? Y/N: y
Enter a Number: 25
2 4 6 8 10 12 14 16 18 20 22 24
Try Again? Y/N: n
您需要将代码复制/粘贴到问题中,而不是将图像链接到代码中。每次循环时,您都会打印“重试”。这就是您想要的吗?您希望问题在外部(之后)循环完成了。@Lowerer好吧,如果他们输入N,它就不会再看了,所以这似乎是他们想要的。看起来你的代码会工作。你试过了吗?@corsiKa对于外循环,是的。对于内循环(在那里),不是。我应该在我的第一个条件中说“内”循环。你好。请不要将文本/代码作为图像/链接()。使用选项更正您的帖子。您需要将代码复制/粘贴到问题中,而不是将图像链接到代码。每次循环时,您都会打印“重试”。这是您想要的吗?您想将该问题放在外部(之后)循环完成了。@Lowerer好吧,如果他们输入N,它就不会再看了,所以这似乎是他们想要的。看起来你的代码会工作。你试过了吗?@corsiKa对于外循环,是的。对于内循环(在那里),不是。我应该在我的第一个条件中说“内”循环。你好。请不要将文本/代码作为图像/链接()。使用选项更正您的帖子。输入一个数字:20 1重试?Y/N Y 2重试?Y/N Y 3重试?Y/N就这样做我的代码有问题,但我仍在学习感谢您的帮助。输入一个数字:20 1重试?Y/N Y 2重试?Y/N Y 3重试?Y/N就这样做我的代码有问题,但我仍在学习谢谢你的帮助,朋友。