所以嗨,我得到无限循环问题我不知道我的代码有什么问题我试图让数字序列格式在底部我认为问题是在我的情况下?
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
答案 0 :(得分:3)
问题在于:while(n!=0)
和此处:for ( int i = 0; i<=n; i++)
。对于while循环,将一直持续到n
等于0.对于for循环,这很可能会一直持续下去。
您的代码有两个问题:
n
)。n
也需要正好0才能停止。根据您的需要,您需要更改条件。根据输出判断,n
需要是正数,因此您需要为n
循环停止的while
规定一些上限。
编辑:你只需要有一个循环来完成你所追求的目标。此外,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++;
}
答案 1 :(得分:2)
两个问题:
if(isset($_POST['todotext'])) {
$chunk = $_POST['todotext'];
$commentArray = explode(" ",$chunk);
.
.
.
$commentArray[$i]='<p class="pos"><img src="imgs/blank.png" width="40" height="40"><br>
'.$commentArray[$i].'</p>';
$together = implode(" ",$commentArray);
echo $together;
答案 2 :(得分:1)
使用'if'条件代替'while'循环
答案 3 :(得分:1)
您必须将while-loop
替换为if-condition
,如此:
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);
}
}
}
}
}
答案 4 :(得分:0)
根据您的回答,我找到了一个有效的解决方案:
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+" ");
}
}
}