[英]Java nested for loop print out
I'm a total beginner to java and need help writing this nested for loop. 我是Java的初学者,需要帮助来编写此嵌套的for循环。 This is the desired output.
这是所需的输出。
2 3 5
5 10 26
11 31 131
23 94 656
I understand that the increment is 2 times the first number + 1, but I don't understand how to create the loop for it. 我知道增量是第一个数字+ 1的2倍,但我不知道如何为它创建循环。
public static void main(String[] args) {
for(int i = 2; i <= 5; i++) {
for(int j = i; j <= i; j++) {
System.out.print(j+(i*j));
}
System.out.println();
}
}
Question is so simple it consists of two things read the pattern and use the appropriate loop statements in java to achieve this. 问题是如此简单,它由两部分组成:读取模式,并在Java中使用适当的循环语句来实现。 Printing them is another task which is not difficult.
打印它们是不难的另一项任务。
@Jonathan your pattern is right but your algorithm is incorrect. @Jonathan您的模式正确,但是算法不正确。 I'm not giving you perfect solution but you have to use proper loop statement to make it efficient.
我没有为您提供完美的解决方案,但您必须使用适当的循环语句才能使其高效。 I'm here giving you a thought so that you can think in this way..hope you get it.
我在这里给您一个想法,以便您可以这样思考..希望您能理解。
public static void main(String[] args) {
/* 2 3 5
5 10 26
11 31 131
23 94 656
*/
int two = 2;
int three = 3;
int five = 5;
int i=0;
//use do-while to print 2 3 5
do{
System.out.println(two +" "+ three +" "+five);
two=two*2+1; // apply math pattern
three= three*3+1;
five= five*5+1;
i++;
}while(i<4);;
}
Please try the following code (I have tested the code, the output is exactly the same as yours): 请尝试以下代码(我已经测试过该代码,输出与您的输出完全相同):
public static void main(String args[]) {
int[][] results = new int[4][3];
results[0][0] = 2;
results[0][1] = 3;
results[0][2] = 5;
for (int i = 1; i < results.length; i++) {
for (int j = 0; j < results[0].length; j++) {
results[i][j] = results[i - 1][j] * results[0][j] + 1;
}
}
for (int i = 0; i < results.length; i++) {
for (int j = 0; j < results[0].length; j++) {
System.out.print(results[i][j] + "\t");
}
System.out.println();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.