Java语言基础------循环流程控制

小灰灰 2022-03-15 12:22 345阅读 0赞

循环流程控制

while循环

  1. while循环原理案例:
  2. 案例代码:

    1. public static void main(String[] args) {
    2. /** * while 循环演示 * 将一个数字按照10进制拆分 */
    3. Scanner console = new Scanner(System.in);
    4. System.out.print("输入一个数字:");
    5. int num = console.nextInt();
    6. while(num>0) {
    7. int last = num%10;
    8. num /= 10;
    9. System.out.println(last);
    10. }
    11. }

do while循环

  1. do while循环原理案例:
  2. 案例代码:

    1. public static void main(String[] args) {
    2. /** * do while 循环演示 * 检查输入分数是否是百分制数据 */
    3. Scanner console = new Scanner(System.in);
    4. int score;
    5. do {
    6. System.out.print("输入分数:");
    7. score = console.nextInt();
    8. }while(!(score>=0 && score <=100));
    9. System.out.println("成功:"+score);
    10. }

for 循环

  1. for 循环原理案例:
  2. 案例代码:

    1. public static void main(String[] args) {
    2. /* * for 循环流程控制 * 控制输出50个Hello World! */
    3. for(int i=0; i<50; i++) {
    4. System.out.println("Hello World!");
    5. }
    6. }
  3. for循环特殊用法

    1. 省略for的第一个表达式:

      1. public static void main(String[] args) {
      2. /* * for 循环的特殊用法 * 1. 默认时候循环变量i的作用域:for循环内部 * 2. 可以将循环变量在循环外部定义,扩大循环 * 变量作用域 * 3. for循环可以省略 初始化 表达式。 */
      3. int i=0;
      4. for(; i<100; i++) {
      5. System.out.println(i);
      6. }
      7. System.out.println(i);
      8. }
    2. 省略递增表达式

      1. public static void main(String[] args) {
      2. /* * for 循环特殊用法,省略递增表达式 * 1. 省略递增表达式,在for循环内部控制递增变量 */
      3. for(int i=0;i<51;) {
      4. System.out.println(i++%3); //0 1 2 0 1 2
      5. }
      6. }
    3. for省略3个表达式

      1. public static void main(String[] args) {
      2. /* * for 循环省略3个表达式 * * 1. for循环省略3个表达方是死循环 * 2. 经常要与 break 配合结束循环 */
      3. Scanner console = new Scanner(System.in);
      4. int score;
      5. for(;;){ //死循环
      6. System.out.print("输入0~100:");
      7. score = console.nextInt(); //88
      8. if(score>=0 && score<=100) {
      9. break;
      10. }
      11. System.out.println("错误!再来");
      12. }
      13. System.out.println(score);
      14. }
    4. 在for循环中定义多个变量

      1. public static void main(String[] args) {
      2. /* * 在for循环中定义多个变量 * 好处是可以将变量的作用域控制在for循环 * 内部,在后续的for循环中可以重新定义变量i j */
      3. for(int i=1, j=6;i<=6; i+=2, j-=2) {
      4. System.out.println("i,j="+i+","+j);
      5. }
      6. //后续的for循环中可以重新定义变量i j
      7. for(int i=1, j=100;i<=6; i+=2, j-=2) {
      8. System.out.println("i,j="+i+","+j);
      9. }
      10. }

发表评论

表情:
评论列表 (有 0 条评论,345人围观)

还没有评论,来说两句吧...

相关阅读