Java入门(二)

运算符

常用的运算符:算数运算符(+-*/%)、自增自减运算符(a++,a--,++a,--a)、赋值运算符(=,+=,-=)、关系运算符、逻辑运算符(||, &&)、三元运算符

注意⚠️ 字符参加加法运算,其实就是拿字符在计算机中存储所表示的数据值来运算的: 'a' 97

       ⚠️ 运算顺序从左到右,字符串参与加法运算,实际上是字符串的拼接

       ⚠️ 当++在变量后面时,先操作,后++,当++在变量前面时,先++,后操作

赋值运算符要注意如下 a+=20 等价于 a = (a的数据类型)(a+20) 蕴含强制类型转换

short s = 1;
s = s + 1;//错误

short s = 1;
s += 1;//正确

三元运算符

int c = (a > b) ? a:b

Scanner

package > import > class

import java.util.Scanner;//调包
public class hello {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);//创建键盘录入对象
        System.out.println("please input");
        int a = sc.nextInt();//获取数据
        int b = sc.nextInt();
        int sum = a + b;
        System.out.println(sum);
    }
}

流程控制语句

if语句

public class hello {
    public static void main(String[] args){
        int a = 10;
        int b = 20;
        //-----------第一种----------------
        if(a != b){
            System.out.println("a == b");
        }
        //-----------第二种----------------
        if(a == b){
            System.out.println("a == b");
        }else{
            System.out.println("a != b");
        }
        //-----------第三种----------------
        if(a == b){
            System.out.println("a == b");
        }else if (a > b){
            System.out.println("a > b");
        }
        else{
            System.out.println("a < b");
        }
    }
}

比较两个输入整数的大小

public class hello {
    public static void main(String[] args){
        Scanner sc =  new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        if(a >= b){
            System.out.println("a >= b");
        }else{
            System.out.println("a < b");
        }
    }
}

Switch语句

import java.util.Scanner;
/*
 * switch语句
 */
public class hello {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int weekday = sc.nextInt();
        switch(weekday){
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            default:
                System.out.println("error");
                break;


        }
    }
}

猜你喜欢

转载自blog.csdn.net/fang19970714/article/details/114040421