我的计划中有后续步骤:
- 我需要输入我想要打印数字的次数。
- 之后我必须输入一个值作为开始。
- 最后,该值必须重复输入打印值的次数。
//这是我所知道的..
import java.util.Scanner;
public class Series{
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
System.out.println("How many numbers do you want to print? ");
int number = keyb.nextInt();
System.out.println("What value would you like to start with? ");
int value1 = keyb.nextInt();
System.out.println("Typ increased value: ");
int increase1 = keyb.nextInt();
System.out.println(value1 + increase1);
}
}
我得到的结果是这样的:
How many numbers do you want to print?
5
What value would you like to start with?
50
Typ increased value:
500
550
我的问题是如何依次打印 5 个数字,每个数字加 +500?
最佳答案
关键在于Java循环。循环允许将同一位代码执行所需的次数,或者直到满足特定条件为止。 for 循环
的语法如下:
for(declaration; loop condition; step)
例如
for(int x = 0; x < 5; x++) {
System.out.println("The number is " + x);
}
这将打印:
The number is 0
The number is 1
...
The number is 4
现在您可以看到这如何应用于您的代码。
一些帮助您入门的伪代码
让我们使用您获得的代码:
System.out.println(value1 + increase1);
所以,你知道这会输出增加的值,但你需要每次都增加它。这意味着您需要跟踪该值:
runningTotal := value1;
for the amount of times to loop {
runningTotal = runningTotal + increase1
output runningTotal
}
现在将其转换为 Java,您就得到了解决方案!
额外阅读
此链接遍历 Java 中提供的所有循环
关于java - 学习基本循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26287356/