1. 用户交互Scanner

// 基础语法
Scanner s = new Scanner(System.in)

// 接收用户数据
public class Control {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);   
        if(s.hasNext()){
            // 判断用户有没有字符串
            // 可以不加判断
            String str = s.next() ;
            // next方法以空格为结束符,不能得到带有空格的字符串
            // nextLine方法以回车为结束符,能得到带有空格的字符串
            // 接收用户字符串
            System.out.println("输出内容为:" + str);
        }
        // 关闭scanner
        s.close();
    }
}
}

scanner其他方法
hasNextInt() ,判断输入是否为Int类型数据(或某种类型)
nextInt(),接收输入的Int类型数据(或某种类型)

2. 选择结构

java本身是顺序结构,一行一行依次执行
选择结构:if、switch

  1. if:单选(if)、双选(if、else)、多选(if、else if、else)、嵌套结构
    if 的多选结构中只会执行一个情况,执行后直接退出结构
  2. switch:通常是switch case 结构
    case穿透:如果匹配到的case分支中没有break终止,则会继续向下执行之后的所有case分支
    所以每个case分支中需要加break
        char grade = 'C';
        switch (grade) {
            case 'A':
                System.out.println("优秀");
            case 'B':
                System.out.println("良好");
            case 'C':
                System.out.println("及格");
            case 'D':
                System.out.println("不及格");
            default:
                System.out.println("差");
        }
        // 代码输出:
        及格
        不及格
        差

switch 判断语句中支持八大类型、字符串
字符串在底层的反编译字节码文件中是变成了hashcode去匹配,所以本质上还是数字

3. 循环结构

循环结构:while、do…while、for

  1. while:
while(条件判断){
    循环体内容
}
  1. do…while :至少会执行一次循环体
do{
    循环体内容
}while(条件判断);
  1. for:
for(初始化;布尔表达式;更新){
    循环体内容
}
// for的死循环写法:
for(;;){
   循环体内容
}

便捷写法:在IDEA中,用for.100,即可生成100的for循环

  1. 增强for循环:主要用于数组和集合的增强型for循环
    有点像python中的数组遍历
int[] numbers = {10,20,30,40};
for(int x : numbers){
    System.out.println(x);
}

4.break、continue

break:强制退出循环
continue:跳过一次循环
goto关键字:跳转到定位的位置,java没有goto,但是有带标签的continue,实现goto,但是不建议使用

int count = 0;
outer:for(int i = 100;i<105;i++){
     for(int j = 2;j<i/2;j++){
        if(i % j == 0){
          continue outer;
          // 可以跳转到外层for循环
        }
   }
}
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐