gpt4 book ai didi

Java 数列循环

转载 作者:行者123 更新时间:2023-12-01 07:22:22 25 4
gpt4 key购买 nike

嗨,我遇到了无限循环问题,我不知道我的代码有什么问题,我正在尝试在底部制作一个数字序列格式,我认为问题出在我的情况下?

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 循环,这很可能会永远持续下去。

您的代码有两个问题:

  1. 如果您提供非负值,这将永远持续下去(因为您始终只递增 n )。
  2. 即使您提供负数,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com