infinite loop, nested loop
1. Infinite loop
for infinite loop
package com.ithema.loop;
public class demo241 {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println("hello word");
}
System.out.println("-----------------------");
for (int i = 0 ; ;i++) {
System.out.println("hello word");
}
System.out.println("-----------------------");
for ( ; ;) {
System.out.println("hello word");
}
}
}
while infinite loop
package com.ithema.loop;
public class demo241 {
public static void main(String[] args) {
while (true) {
System.out.println("hello word");
}
}
}
do-while infinite loop
package com.ithema.loop;
public class demo241 {
public static void main(String[] args) {
do{
System.out.println("hello word");
} while(true);
}
}
2. Loop nesting
package com.ithema.loop;
public class demo241 {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
String out = String.format("第 %s 天 第 %s 句:",i+1,j+1);
System.out.println(out+"我哈哈哈");
}
}
}
}
Print three rows and four columns of asterisks
package com.ithema.loop;
public class demo241 {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
3. Jump keywords
break
package com.ithema.loop;
public class demo241 {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("hahah");
if(i==3){
break;
}
}
}
}
output
hahah
hahah
hahah
continue
package com.ithema.loop;
public class demo241 {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if(i==3){
continue;
}
System.out.println("hahah"+i);
}
}
}
output
hahah1
hahah2
hahah4
hahah5
4. Generate random numbers
random
hot key:ctrl+alt +t
package com.ithema.loop;
import java.util.Random;
public class demo241 {
public static void main(String[] args) {
Random r = new Random();
int i = 0;
while (i < 5){
int data = r.nextInt(10);
System.out.println(data);
i++;
}
}
}
Generate random numbers from 1-10
package com.ithema.loop;
import java.util.Random;
public class demo241 {
public static void main(String[] args) {
Random r = new Random();
int i = 0;
while (i<10) {
int data = r.nextInt(10);
System.out.println(data+1);
i++;
}
}
}
the case
Enter the number, the prompt is bigger than the real value, until the number is guessed!
package com.ithema.loop;
import java.util.Random;
import java.util.Scanner;
public class demo241 {
public static void main(String[] args) {
Random r = new Random();
int data = r.nextInt(10) + 1;
while(true){
// 键盘输入数字
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个数字: ");
int a = scanner.nextInt();
if (a == data){
System.out.println("猜中了");
scanner.close();
break;
}
else if (a > data){
System.out.println("猜大了");
}
else{
System.out.println("猜小了");
}
}
}
}
output
请输入一个数字: 4
猜小了
请输入一个数字: 10
猜大了
请输入一个数字: 8
猜大了
请输入一个数字: 6
猜中了