[英]JAVA how to simplify iteration
How can i simplify this code using loops or some other kind of methods?如何使用循环或其他类型的方法简化此代码? For example i need to iterate not just 4 times but n times?例如,我不仅需要迭代 4 次,还需要迭代 n 次? For example now i am doing 4 calculations and 4 system.out.prints, how can i change or what i can use that those 4 calculations would be looped automatically, because for example if i need to do like 100 or more calculations not just 4.例如,现在我正在做 4 个计算和 4 个 system.out.prints,我如何更改或我可以使用的内容将自动循环这 4 个计算,因为例如,如果我需要做 100 个或更多的计算而不仅仅是 4 个.
public class A {
public static void main(String[] args) {
int A = 22;
int APRme = 12;
int I = APRme * A % 10;
int AR1 = I * A % 10;
int AR2 = AR1 * A % 10;
int AR3 = AR2 * A % 10;
System.out.println(I);
System.out.println(AR1);
System.out.println(AR2);
System.out.println(AR3);
}
}
You can create a loop which would perform the calculations a given number (n)
of times.您可以创建一个循环来执行给定次数(n)
的计算。 For example, your current code does it four times:例如,您当前的代码执行四次:
public class A {
public static void main(String[] args) {
int A = 22;
int APRme = 12;
int result = APRme;
int n = 4; // How many times would you like to do the calculations
for (int i = 1; i <= n; i++) {
result = result * A % 10;
System.out.println(result);
}
}
}
In this particular example I would leave the code exactly as it is right now.在这个特定的例子中,我会保留代码完全按照现在的样子。 The nice thing about this code is that it is short and readable, and when you step through it using a debugger, you can inspect each intermediate result.这段代码的优点在于它简短易读,当您使用调试器逐步执行它时,您可以检查每个中间结果。 In case of a bug this will show you exactly at which point the error happened.如果出现错误,这将准确显示错误发生的时间点。
If you still want to write it as a loop, it is written:如果还想写成循环,写成:
int intermediate = start;
for (int i = 0; i < 4; i++) {
intermediate = intermediate * A % 10;
System.out.println(intermediate);
}
The line that starts with for
looks so complicated for historic reasons.由于历史原因,以for
开头的行看起来如此复杂。 It basically just says "do the following 4 times".它基本上只是说“做以下4次”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.