Java流程控制

Java流程控制

scanner

public static void test6(){
       Scanner scanner = new Scanner(System.in);//创建对象
       System.out.println("请输入:");

       if(scanner.hasNextLine()){//程序停在判断这一步,enter后往下走
           System.out.println("输入了没?");
           String s = scanner.nextLine();
           System.out.println(s);
      }
       /*
       请输入:
       测试
       
       输入了没?
       测试
        */
       scanner.close();
  }
public static void test7(){
       //输入多个数字,并求其总和与平均值,每输入一个数字用回车确认,输入非数字来结束输入
       Scanner scanner = new Scanner(System.in);
       System.out.println("请输入:");

       double sum=0 ;//总数
       int count=0;//计数
       //通过循环判断是否还有输入double类型数据,
       while (scanner.hasNextDouble()){
           double d = scanner.nextDouble();
           count++;
           sum=sum+d;
           System.out.println("你输入了第"+count+"个数,当前结果sum="+sum);
      }
       System.out.println(count+"个输入数字和为"+sum);
       System.out.println(count+"个数的平均值为"+(sum/count));

       scanner.close();
  }

嵌套循环

 public static void test8(){
       //打印九九乘法表
       for(int i=1;i<=9;i++){//一到九行
           for(int j=1;j<=i;j++){//每行多少列
               System.out.print(j+"*"+i+"="+(i*j)+"\t");
          }
           System.out.println();//换行
      }
  }
public static void test11() {
       /*
       打印倒三角形,五行
        *********
         *******
          *****
           ***
            *
        */
       for (int i = 1; i <= 5; i++) {//五行,三角形竖切分四部分
           for (int j = 1; j <= i; j++) {//每行先输出空格-递增
               System.out.print(" ");
          }
           for (int j = 5; j >= i; j--) {
               System.out.print("*");//再输出前半部分*
          }
           for (int j = 5; j > i; j--) {
               System.out.print("*");//再输出后半部分*
          }
           //最后一部分空格不用输入了
           System.out.println();//换行
      }
  }

continue,break,goto(标签)

continue和break通常只中断当前循环,可用标签中断到存在标签的地方

    public static void test9(){
       //打印101到150之间的质数
       next:for(int i=101;i<150;i+=2){//2以外偶数不是质数
           for(int j=2;j<i/2;j++){//从2甚至是3开始到i/2不被整除就是质数
               if(i%j==0){
                   continue next;//返回标签
              }
          }
           System.out.print(i+" ");
      }
  }

 

//        test2();
// test3();
// test4();
// test5();
// test6();
// test7();
// test8();
// test9();
// test10();
// test11();
posted on 2020-08-04 11:41  门之钥  阅读(10)  评论(0)    收藏  举报