所以我的任务是根据我在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新手,这是我的第一个编程语言,我不知道我在做什么。一点帮助可能会有帮助。谢谢你!
根据您的描述,这里有一个简单的程序。
指出:
-
变量int[] numbers和布尔值foundNum从未被使用
-
你只需要一个for循环。
-
关闭对象扫描器是一个很好的做法。
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
,step
和end
变量足以在一个循环中产生您的输出。
for (int i = start; i <= end; i += step) {
System.out.print(i + " "); // just an example - you could add the number to a list instead
}