作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
嗨,我遇到了无限循环问题,我不知道我的代码有什么问题,我正在尝试在底部制作一个数字序列格式,我认为问题出在我的情况下?
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 需要恰好变为 0 才能停止。根据您需要执行的操作,您需要更改条件。从输出来看,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++;
}
关于Java 数列循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32782753/
我是一名优秀的程序员,十分优秀!