常见的是两层嵌套
for for
for while
while while
while for
/* 循环的嵌套: */ public class NestDemo1{ public static void main(String[] args){
for(int i =1; i<=5;i++){//外层循环 //System.out.println(); for(int j =0;j<3;j++){//内层循环 System.out.println("hello"); } System.out.println("---------") } } }
/* 用嵌套打印等腰三角形 */ public class ForForDemo1{ public static void main(String[] args){ //for(int i =0;i<10;i++){ int i = 0; while (i<10){ for(int j =0;j<10-i;j++){ System.out.print("$"); } i++; System.out.println(); } //} } } /*public class ForForDemo1{ public static void main(Stirng[] args){ for(int i = 0;i<=10;i++){ for(int j=0;j<11-i;j++){ System.out.print("s"); }System.out.println(); } } } */
/* 从键盘上输入一个数,和随机数比较,并给出大小提示 */ /* import java.util.Scanner; public class GuessNumber{ public static void main (String[] args){ Scanner s =new Scanner(System.in); int r = (int)(Math.random()*100 + 1); for(;;){ System.out.print("输入一个数:(1-100)"); int n = s.nextInt(); if(n==r){ System.out.println("猜中了"); break; }else if(n<r){ System.out.println("小了"); }else if(n>r){ System.out.println("大了"); } } } } */ //import java.util.Scanner; public class GuessNumber{ public static void main (String[] args){ //Scanner s =new Scanner(System.in); int r = (int)(Math.random()*(88-55+1) + 33); for(;;){ //System.out.print("输入一个数:(33-88)"); // int n = s.nextInt(); int n = (int)(Math.random()*(88-55+1)+33); System.out.print(n); if(n==r){ System.out.println("猜中了"); //break; continue; }else if(n<r){ System.out.println("小了"); }else if(n>r){ System.out.println("大了"); } } } }