流程控制

Scanner

通过Scanner类获取用户的输入

public class HelloWord {
   public static void main(String[] args){
       Scanner a = new Scanner(System.in);
       System.out.println("使用next接受输入信息:");
       //判断用户是否输入字符串
       if (a.hasNext()){
           String str = a.next();//程序会等待用户输入完毕
           System.out.println("使用next()输出的内容为:"+str);
      }
     /* 使用next接受输入信息:
         Hello Word!
         使用next()输出的内容为:Hello*/
       //用完关掉 节省资源
       a.close();
       System.out.println("使用nextLine接收");
       Scanner b = new Scanner(System.in);

       if (b.hasNext()){
           String str2 = b.nextLine();
           System.out.println("使用nextLine输出的内容为:"+str2);
      }
       b.close();
    /*   Hello word!
           使用nextLine输出的内容为:Hello word!*/
  }
}
next():
  1. 一定要读取到有效字符后才可以结束输入

  2. 对输入有效字符之前遇到的空白,next()将自动将其去掉

  3. 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符

  4. next()不能去掉带有空格的字符串

nextLine():
  1. 以Enter为结束符 也就是说:nextLine()方法返回的是输入回车之前的所有的字符

  2. 可以获得空白

顺序结构

java的基本结构。是任何一个算法都离不开的一种基本算法。

选择结构

if单选择结构
if(){
   
}

 

if双选择结构
if(){
   
}else{
   
}

 

if多选择结构
if(){

}else if{

}else if{

}else{

}

 

嵌套的if结构
if(){
   if(){
       
  }
}

 

switch多选择结构

判断 一个变量一系列值中的某个值 是否相等,每个值称为一个分支。

switch语句中变量类型可以是byte、short、int、char

javaSE7 支持String

同时 case 标签必须为 字符串常量或字面量

 char score = 'F';
      switch (score){
          case 'A':
              System.out.println("优秀");
              break;
          case 'B':
              System.out.println("良好");
              break;
          case 'C':
              System.out.println("不及格");
              break;
          default:
              System.out.println("未知等级");
      }

循环结构

while循环
  int i = 0;
      int sum = 0;
      while(i<=100){
          sum = sum + i;

          if (i == 100){
              System.out.println(sum);
          }
          i++;
      }

 

do........while循环

while 和 do whie的区别?

while先判断后执行

do...while 先执行后判断,至少执行一次

 int a = 0;
   while(a<0){
       System.out.println(a);
       a++;
  }
       System.out.println("=================");
   do {
       System.out.println(a);
       a++;
  }while(a<0);
//控制台输出
//=================
//0

 

for循环

for是最有效最灵活的循环结构;

IDER 快捷键 100.for

for(int i = 0;i<100;i++){
   
}

 

增强型for循环
posted on 2022-05-31 16:24  可惜君已逝i  阅读(27)  评论(0)    收藏  举报