Java中嵌套循环的类型 [英] Types of Nested Loops in Java
问题描述
那样做,如果{if {if {if {if {
>也是这样的。只需要更多的更多类型的嵌套循环的想法。 如果你可以写下一些例子。我会很高兴。感谢您。
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ int i = 0; (j = 1; j <= 5; j ++){
if(j == 1 || j == 5){
i = 4;
} else {
i = 1;
for(int x = 0; x System.out.print(**);
}
System.out.println();
$ div class =h2_lin>解决方案
/ Java有4个循环结构: Java没有 这是一个典型的简单的三角型嵌套循环,其中内部循环的迭代次数取决于在外部循环中迭代的值: 下面是一个例子一个配对类型的嵌套循环,其中两个循环是相互独立的,使用for-each构造: 循环可以像Java中实际需要的一样嵌套:实际的限制。
$ b $ ul
代表
声明
for
Statement (又名 for-each
)
while
语句
do Statement
(又名 do-while
)
goto
(这不是真的需要)
参见
示例
for(int i = 1; i <= 5; i ++){//打印:
for(int j = 0; j System.out.print(*); // **
} // ***
System.out.println(); // ****
} // *****
pre $ code > int [] numbers = {1,2,3}; //打印://如果交换:
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
for-each
construct,它缺少显式的索引,使得两个循环的独立性显而易见:你可以在上面的代码中交换两个 for
语句,你仍然可以得到所有的对,尽管以不同的顺序列出。
<$ c $ c>扫描仪sc =新扫描仪(我们再去); // print:
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);
$ b $ p
$ b下面是一个例子,显示
do-while
不同于while-do
和:
int x = 0;
do {
System.out.println(Hello !!!);
} while(x!= 0);
上面的循环打印
Hello !!!
:在检查结束条件之前执行do-while
的主体
一个更详细的例子
下面是一个嵌套循环逻辑的例子,但重构成方法使事情更具可读性。这对于初学者来说是非常重要的:仅仅因为你可以根据自己的想法在不同层次上嵌套循环,并不意味着你应该。通过分解这样的逻辑,程序变得更加模块化和可读,每个逻辑独立,可以被测试和重用等等。在$
char []
in-place中的一个单词的字母。
pre $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);
(int i = 0; iswap(arr,from + i,to-1-i)
public static void main(String [] args){
char [] sentence =在句子中反转字母.toCharArray();
final int L = sentence.length;
int last = 0;
for(int i = 0; i <= L; i ++){
if((i == L)||(sentence [i] =='')){
(句子,最后,我);
last = i + 1;
}
}
System.out.println(new String(sentence));
//打印
$ p
$这个例子在中也是很有启发性的,尽管它基本上是一个嵌套的循环算法,但它实际上是 O(N)O(N ^ 2)
是错误的 - 它实际上取决于算法本身,而不仅仅是物理结构。 / b>
嵌套循环算法
这些是传统的算法使用嵌套循环(至少在他们的天真形式):
$ ul $ b $ li $ $ c $ O> O(N ^ 2)排序算法:
- Bubble sort
- 选择排序
- 插入排序
- 矩阵乘法
- 表填充动态编程算法
- Levenshtein distance (
O(N ^ 2)
,字符串编辑距离) - Floyd-Warshall算法 (
O(N ^ 3)
,图中所有对最短路径)
这些都不是一个详尽的示例,但是它应该很好地介绍循环算法的各种嵌套
适合初学者。
I have a simple question. I have to find out many nested loops as possible in java. I have something like for loop and if statement inside. i know that we can do like
if{if{if{if{
something like that too. 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 has 4 looping constructs:
- JLS 14.14 The
for
Statement - JLS 14.12 The
while
Statement - JLS 14.13 The
do
Statement (aka "do-while
")
Java does not have
goto
(which isn't really needed anyway).See also
Examples
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:
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 twofor
statements in the above code, and you'd still get all pairs, though listed in a different order.This use of a
boolean
method for awhile
loop (this one fromjava.util.Scanner
) is typical: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 fromwhile-do
andfor
:int x = 0; do { System.out.println("Hello!!!"); } while (x != 0);
The above loop prints
Hello!!!
: the body of ado-while
is executed before the termination condition is checked.
A more elaborate example
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.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)
! It's a mistake to think that any doubly nested-loop algorithm must beO(N^2)
-- it really depends on the algorithm itself more than just the physical structure.
Nested-loop Algorithms
These are classical algorithms traditionally implemented using nested loops (at least in their naive forms):
O(N^2)
Sorting algorithms:O(N^3)
triply nested loop algorithms:- Table-filling dynamic programming algorithms
- Levenshtein distance (
O(N^2)
, string edit distance) - Floyd-Warshall Algorithm (
O(N^3)
, all-pairs shortest path in graph)
- Levenshtein distance (
These are far from an exhaustive sampling, but it should provide a good introduction to a variety of nested
for
loops algorithms for beginners.这篇关于Java中嵌套循环的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Levenshtein distance (
$ li $ code> O(N ^ 3)三重嵌套循环算法:
$ b