[英]Types of Nested Loops in Java
I have a simple question. 我有一个简单的问题。 I have to find out many nested loops as possible in java. 我必须在java中找到许多嵌套循环。 I have something like for loop and if statement inside. 我有类似for循环和if语句的内容。 i know that we can do like if{if{if{if{
something like that too. 我知道我们可以做if{if{if{if{
类似的东西)。 just need some more idea of more types of nested loops. 只需要了解更多类型的嵌套循环。
if you can write down some examples. 如果你能写下一些例子。 I'll be very glad. 我会很高兴的。 thank you. 谢谢。
public class Test {
public static void main (String []args) {
int i = 0;
for(int j = 1; j <= 5; j++) {
if(j == 1 || j == 5) {
i = 4;
} else {
i = 1;
}
for(int x = 0; x < i; x++) {
System.out.print("**");
}
System.out.println();
}
}
}
You can nest as many for
/ while
loops as you'd practically want in Java: there's no practical limit. 您可以像Java中实际需要的那样嵌入尽可能多的for
/ while
循环:没有实际限制。
Java has 4 looping constructs: Java有4个循环结构:
for
Statement JLS 14.14 for
Statement
for
Statement JLS 14.14.1基本for
声明 for
Statement (aka " for-each
") JLS 14.14.2增强for
Statement (又名“ for-each
”) while
Statement JLS 14.12 while
声明 do
Statement (aka " do-while
") JLS 14.13 do
语句 (又名“ do-while
”) Java does not have goto
(which isn't really needed anyway). Java没有goto
(无论如何都不需要)。
for
Statement Java Nuts和Bolts / for
Statement for-each
loop Java语言指南/ for-each
循环 This is a typical example of a simple "triangle"-type nested loop, where the number of iteration of the inner loop depends on the value being iterated in the outer loop: 这是一个简单的“三角形”类型嵌套循环的典型示例,其中内循环的迭代次数取决于外循环中迭代的值:
for (int i = 1; i <= 5; i++) { // prints:
for (int j = 0; j < i; j++) { // *
System.out.print("*"); // **
} // ***
System.out.println(); // ****
} // *****
Here's an example of a "pairing"-type nested loop, where the two loops are independent of each other, using the for-each construct: 下面是一个“配对”类型嵌套循环的示例,其中两个循环使用for-each结构彼此独立:
int[] numbers = { 1, 2, 3 }; // prints: // if swapped:
char[] letters = { 'A', 'B', 'C' }; // 1 A // 1 A
// 1 B // 2 A
for (int number : numbers) { // 1 C // 3 A
for (char letter : letters) { // 2 A // 1 B
System.out.println(number + " " + letter); // 2 B // 2 B
} // 2 C // 3 B
} // 3 A // 1 C
// 3 B // 2 C
// 3 C // 3 C
The for-each
construct, which lacks explicit indices, makes the indepedence of both loops obvious: you can swap the two for
statements in the above code, and you'd still get all pairs, though listed in a different order. for-each
构造缺少显式索引,使得两个循环的独立性显而易见:您可以在上面的代码中交换两个for
语句,并且您仍然可以获得所有对,尽管以不同的顺序列出。
This use of a boolean
method for a while
loop (this one from java.util.Scanner
) is typical: 对while
循环使用boolean
方法(这个来自java.util.Scanner
)是典型的:
Scanner sc = new Scanner("here we go again"); // prints:
while (sc.hasNext()) { // hereeeee
String s = sc.next(); // weeeee
char lastChar = s.charAt(s.length() - 1); // gooooo
for (int i = 0; i < 4; i++) { // againnnnn
s += lastChar;
}
System.out.println(s);
}
And here's an example that shows how do-while
is different from while-do
and for
: 这里有一个例子,展示了do-while
与while-do
和for
不同之处:
int x = 0;
do {
System.out.println("Hello!!!");
} while (x != 0);
The above loop prints Hello!!!
以上循环打印Hello!!!
: the body of a do-while
is executed before the termination condition is checked. :在检查终止条件之前执行do-while
的主体。
Here's an example of a nested-loop logic, but refactored into methods to make things more readable. 这是一个嵌套循环逻辑的示例,但重构为方法以使事物更具可读性。 This is something that is important for beginners to learn: just because you can physically nest loops as many levels as you want, doesn't mean you should . 这对于初学者来说很重要: 只是因为你可以根据需要在物理上嵌套循环,并不意味着你应该这样做 。 By breaking apart the logic like this, the program becomes more modular and readable, and each logic stands on its own and can be tested and reused, etc. 通过拆分这样的逻辑,程序变得更加模块化和可读,并且每个逻辑都独立存在,可以进行测试和重用等。
This snippet reverses the letters of a word in a char[]
in-place. 此片段在原位上反转char[]
中单词的字母。
static void swap(char[] arr, int i, int j) {
char t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
static void reverse(char[] arr, int from, int to) {
int N = (to - from);
for (int i = 0; i < N / 2; i++) {
swap(arr, from+i, to-1-i);
}
}
public static void main(String[] args) {
char[] sentence = "reversing letters of words in sentence".toCharArray();
final int L = sentence.length;
int last = 0;
for (int i = 0; i <= L; i++) {
if ((i == L) || (sentence[i] == ' ')) {
reverse(sentence, last, i);
last = i + 1;
}
}
System.out.println(new String(sentence));
// prints "gnisrever srettel fo sdrow ni ecnetnes"
}
This example is also instructive in that even though it's essentially a nested loop algorithm, it's actually O(N)
! 这个例子也很有启发性, 即使它本质上是一个嵌套循环算法,它实际上是 O(N)
! It's a mistake to think that any doubly nested-loop algorithm must be O(N^2)
-- it really depends on the algorithm itself more than just the physical structure. 认为任何双嵌套循环算法必须是O(N^2)
- 它实际上取决于算法本身而不仅仅是物理结构。
These are classical algorithms traditionally implemented using nested loops (at least in their naive forms): 这些是传统上使用嵌套循环实现的经典算法(至少以它们的天真形式):
O(N^2)
Sorting algorithms: O(N^2)
排序算法:
O(N^3)
triply nested loop algorithms: O(N^3)
三重嵌套循环算法:
O(N^2)
, string edit distance) Levenshtein距离 ( O(N^2)
,字符串编辑距离) O(N^3)
, all-pairs shortest path in graph) Floyd-Warshall算法 ( O(N^3)
,图中的所有对最短路径) These are far from an exhaustive sampling, but it should provide a good introduction to a variety of nested for
loops algorithms for beginners. 这些远非详尽的采样,但它应该为初学者提供各种嵌套for
循环算法的良好介绍。
The code if { if { if { ... } } }
is not an example of nested loops. if { if { if { ... } } }
的代码不是嵌套循环的示例。 if
does not use loop. if
不使用循环。
Looping expressions are for example for
and while
. 循环表达式例如是for
和while
。
Loops can be done using the 3 basic loop statements: for
, while
and do..while
. 循环可以使用3个基本循环语句来完成: for
, while
和do..while
。 However, if your question is about how many types of nested loops are possible in Java, I'd say LOTS , since you can arrange and mix them as you wish. 但是,如果您的问题是关于Java中可能有多少种类型的嵌套循环,我会说很多 ,因为您可以根据需要排列和混合它们。
I like the previous answer, but in an attempt to answer directly this curious question: 我喜欢上一个答案,但试图直接回答这个奇怪的问题:
if-else
is not a loop type. if-else
不是循环类型。 Java has for
, while
, and do-while
loops. Java有for
, while
和do-while
循环。 You could argue the the "foreach" syntax for for
loops, introduced in Java 5, is a different kind of loop for your purpose. 您可以认为Java 5中引入的for
循环的“foreach”语法是一种不同类型的循环,用于您的目的。 But really it is just shorthand for writing a while loop. 但实际上它只是写一个while循环的简写。
But all of these "different" loop types are just language constructs. 但所有这些“不同”的循环类型只是语言结构。 In the byte code that is compiled, they're not intrinsically different. 在编译的字节代码中,它们本质上不同。
I guess it depends on the compiler. 我想这取决于编译器。 I wrote a simple test program that generates Java files with different levels of loop nesting. 我写了一个简单的测试程序,它生成具有不同级别的循环嵌套的Java文件。
import java.io.BufferedWriter;
import java.io.FileWriter;
public class NestingTest
{
public static void main(String[] args) throws Exception
{
for (int n = 1; n < 10000; ++n)
{
String className = "test" + n;
FileWriter fw = new FileWriter("f:/test/" + className + ".java");
BufferedWriter o = new BufferedWriter(fw);
o.write("public class ");
o.write(className);
o.write("\n{\npublic static void main(String[] args) {\n");
for (int i = 0; i < n; ++i)
{
o.write("while(true) {\n");
}
for (int i = 0; i < n; ++i)
{
o.write("}\n");
}
o.write("}\n}\n");
o.close();
}
}
}
Once the files are generated, you do a manual binary search. 生成文件后,您可以进行手动二进制搜索。 Compile test5000. 编译test5000。 If it succeeds, compile test7500, and if it doesn't, compile test2500. 如果成功,编译test7500,如果没有,编译test2500。 After 13 or 14 steps, you should come to a conclusion. 经过13或14步后,您应该得出结论。
My compiler's sweetspot seems to be 5345 levels of nesting for this simple program, so I guess in practice it doesn't matter at all. 对于这个简单的程序,我的编译器的甜点似乎是5345级别的嵌套,所以我想在实践中它根本不重要。
是的,筑巢没有限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.