根据输入:START, STEP和END生成一个系列

  • 本文关键字:END 个系列 STEP START java
  • 更新时间 :
  • 英文 :


所以我的任务是根据我在START、STEP和END上的输入生成一系列数字。例如:如果我在开始处输入5,在步骤处输入2,在结束处输入13,那么输出将是:

5、7、9、11、13

import java.util.Scanner;
public class SeriesOfNumbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int [] numbers = {1 ,2 ,3 ,4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
int start = 0;
int step = 0;
int end = 0;
boolean foundNum = false;


System.out.print("START: ");
start = scan.nextInt();
for(start = 0; start <= numbers.length; start++) {
if(start == numbers.length) {
foundNum = true;
break;
}
}

System.out.print("STEP: ");
step = scan.nextInt();
for(step = 0; step <= numbers.length; step++) {
if(start == numbers.length) {
foundNum = true;
break;
}
}
System.out.print("END:");
end = scan.nextInt();
for(end = 0; end <= numbers.length; end++) {
if(end == numbers.length) {
foundNum = true;
break;
}
}
if(foundNum) {
System.out.print("The output will be: ");
}
}
}

预期输出:

START: 5
STEP: 3
END: 20
The output will be: 5 8 11 14 17 20

因为我是JAVA新手,这是我的第一个编程语言,我不知道我在做什么。一点帮助可能会有帮助。谢谢你!

根据您的描述,这里有一个简单的程序。

指出:

  1. 变量int[] numbers和布尔值foundNum从未被使用

  2. 你只需要一个for循环。

  3. 关闭对象扫描器是一个很好的做法。

import java.util.Scanner;
public class SeriesOfNumbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("START: ");
int start = scan.nextInt();

System.out.print("STEP: ");
int step = scan.nextInt();

System.out.print("END: ");
int end = scan.nextInt();
System.out.print("The output will be: ");
for (int i = start; i <= end; i += step) {
System.out.print(i + " ");
}
scan.close();
}

}

这里不需要多个循环。您的start,stepend变量足以在一个循环中产生您的输出。

for (int i = start; i <= end; i += step) {
System.out.print(i + " "); // just an example - you could add the number to a list instead
}

最新更新