12.2※、for循环练习

eg --> for练习:

先总体大思路 然后再用细节部分 逻辑要严谨【思路\步骤】 【规律】 【技术点\实现代码】

eg1: 输入三个整数,实现a

/*** @author Lantzrung* @date 2022年7月17日* @Description*/public class Demo{public static void main(String[] args){//1、创建Scanner扫描器Scanner sc = new Scanner(System.in);//2、获取3个整数System.out.println("请输入整数a:")int a = nextInt();System.out.println("请输入整数b:")int b = nextInt();System.out.println("请输入整数c:")int c = nextInt();//输入就当a是65 b是32 c是106//3.排序条件 使用三个if语句//--a>b交换    简称走位if{a>b}{//条件成立时  目的:就是将a和b互换; cause:a的值大于b 所以要互换int temp = a;//将a赋值给temp 故 现在temp和a等于65a = b;//将b赋值给a 故现在b和a是32b = temp;//将temp=65的值给b  //最终将b和a的数值互换了 b等于=65 而a=32}//--a>c交换if(a>c){int temp = a;a = c;c = temp;} //--b>c交换if(b>c){int temp = b;b = c;c= temp; }System.out,printf("a=%d,b=%d,c=%d"a,b,c);//a=a的值,b=b的值,c=c的值sc.close();//释放资源}}

eg2:练习:7行三角形输出

规律:

每一行的星号:2*n-1;

每一行的空格:总行数-当前行的序号

总行数为7 [7-i]

/*** @author Lantzrung* @date 2022年7月17日* @Description*/public class Demo01{public static void main(String[] args){
效果图: //     一共7行数   【思路\步骤】 【规律】 【技术点\实现代码】//       空格数:              星号数://        6         *         1  //	      5        ***        3//	      4       *****       5//	      3      *******      7//	      2     *********     9//	      1    ***********   11//	      0   *************  13// 1、最外层的循环为7行 现行数为i 最外层嵌套整个两个内循环for (int i = 0; i <= 7; i++) {// 2、空格 【7(总行数)-现行数(i)】 不换行  o的初始值要为1for (int o = 1; o <= (7 - i); o++) {System.out.print(" ");}// 3、星号 【2*现行数(i)-1】 不换行  o的初始值要为1for (int o = 1; o <= (2 * i - 1); o++) {System.out.print("*");}// 4、换行1  换行是使输出结果切换行数达到效果图System.out.println();}}}

eg2:练习:任意行数三角形输出增强版

/*** @author Lantzrung* @date 2022年7月17日* @Description*/public calss Demo2{public static void main(String[] args){//就是将本来的7行 现增强版用一个n变量重新定义总行数 所以以下数据要作一部分修改int n = 13;// 1、最外层循环 里面的行数要修改 for (int i = 0; i <= n; i++) {// 2、空格行数也是要修改 【总行数-现行数(i)】 不换行for (int o = 1; o <= (n - i); o++) {System.out.print(" ");}// 3、星号行数不变用 【2*现行数(i)-1】 不换行for (int o = 1; o <= (2 * n - 1); o++) {System.out.print("*");}// 4、换行1  换行是使输出结果切换行数达到效果图System.out.println();}}
}

eg3:练习 五十先令 男人3先令 女人2先令 小孩1先令 百鸡百钱:

有30人,可能包括男人、女人、小孩,他们在一饭店共消费50先令,其中每个男人花3先令,每个女人花2先令,每个小孩花1先令,求男人、女人、小孩各多少人?【30人50先令】【百鸡百钱】

/*** @author Lantzrung* @date 2022年7月17日* @Description*/public class Demo3{public static void main(String[] args){//先定义男人 man  max-->总共50先令 但每个男人花3先令 --> :50/3≈16for(int man = 0;man<=16;man++){//定义女人 woman   max-->50/2=25for(int woman = 0;woman<=25;woman++){//定义小孩   child  max-->50/1 = 50  child for(int child = 0;child<=50;child++){//统计人数int number = man + woman + child;//统计金额int total = man*3+ woman*2 + child;//判断if(number==30&&total==50){System.out.printf("男人:%d,女人:%d,小孩:%d \n", man ,woman ,child); }                           }       }}}
}