Java数字序列循环
所以你好我得到无限循环问题我不知道我的代码是什么错我试图使数字序列格式是在底部我认为问题是在我的情况?Java数字序列循环
import java.util.Scanner;
public class tester {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
while(n!=0) { //is this right?
for (int i = 0; i<=n; i++) {
if(i%2==0) {
n += 2;
System.out.print(n);
} else {
n += 3;
System.out.print(n);
}
}
}
}
}
输出我想要得到
Enter how many numbers to display : 5
1 3 6 8 11
2.
Enter how many numbers to display : 16
1 3 6 8 11 13 16 18 21 23 26 28 31 33 36 38 //but im getting infinite loops
// the sequence pattern is +2 then +3
的问题是在这里:while(n!=0)
这里:for (int i = 0; i<=n; i++)
。对于while循环,将继续前进,直到n
等于0.对于for循环,这很可能会持续进行。
您的代码有两个问题:
- 如果你提供一个非负值,这会一直下去,直到永远(因为你永远只增加
n
)。 - 即使你确实提供了一个负数,
n
也需要完全停止。
根据您需要做什么,您将需要更改条件。从输出结果来看,n
需要是正数,因此您需要规定n
的一些上限范围,其中while
循环将停止。
编辑:你只需要有1循环做你以后的事情。另外,n
表示元素的数量,因此在整个程序执行过程中需要保持固定。在你的情况下,你一直在增加它。
Scanner x = new Scanner(System.in);
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
int count = 0;
int i = 1;
while (count < n) { //is this right?
if (count % 2 == 0) {
System.out.print(i + " ");
i += 2;
} else {
System.out.print(i + " ");
i += 3;
}
count++;
}
使用 '如果' 条件的地方 '而' 循环
仍然给出了一个无限循环,我认为它在if语句中的状态? – Jake
雅赖特,你正在改变循环中的'n'值,这也是无限循环的原因。 'for'循环中的' – KishoreReddy
','i'递增1步,同时'n'递增2或3步。最好使用另一个局部变量,而不是改变'n'值。 – KishoreReddy
两个问题:
int stop = n; // declare one local var to stop the for loop
if (n != 0) { //switch to if condition
for (int i = 0; i <= stop; i++) {
//loop's exit condition wasn't met because 'n' was also being incremented
if (i % 2 == 0) {
n += 2;
System.out.print(n+" ");
} else {
n += 3;
System.out.print(n+" ");
}
}
}
你必须像这样有if-condition
取代你while-loop
:
import java.util.Scanner;
public class tester {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
int stop = n;
if(n!=0) { //if statement checks if n!=0
for (int i = 0; i<=stop; i++) {
//stop replaces n because n is incremented in your for-loop
if(i%2==0) {
n += 2;
System.out.print(n);
} else {
n += 3;
System.out.print(n);
}
}
}
}
}
仍然给出了无限循环 – Jake
你是否也改变了for循环?它不应该循环无限 –
根据你的回答,我发现了一个可行的解决方案:
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
int k = -2; // so that it starts with 1 when i add +3
int stop = n-1;
if(n!=0) {
for (int i = 0; i<=stop; i++) {
if(i%2==0) {
k += 3;
System.out.print(k+" ");
} else {
k += 2;
System.out.print(k+" ");
}
}
}
虽然发布您的最终解决方案作为答案是有帮助的,但一定要将其他答案标记为已接受,无论哪个答案最能帮助您获得解决方案。 – CubeJockey
好,然后把你upvotes:D我的answere应该已经摆脱了infinit循环... –
不需要'while'。 – Satya