Java基础入门

Java程序基础

在学习狂神的视频课程和廖雪峰的教程时所记录的笔记
比较基础 适合有其他语言基础的入门学习,了解基本语法

程序基本结构

/**
*创建文档注解(很少用)
*/
//单行注解
/*块注解*/
public class Hello{     //类(名称首字母要大写且与源文件文件名相同)
    public static void main(String[] args){     //创建一个静态main方法(方法名首字母小写)(IDEA中快捷psvm)
        System.ou.println("Hello");             //标准输出格式,println自动换行输出(IDEA中快捷sout)
    }
}//Class定义结束

类名必须以英文字母开头,后接字母数字_

习惯大写字母打头

Class内部可定义若干方法(main之类的)

命名规则与类相同

首字母小写

变量与数据类型

基本与c一致

整型 short int long(后面要加L)

浮点型 float(后面要加f) double 浮点数运算有误差

布尔型(逻辑运算) boolean

字符型 char

字符串型(引用类型) String(不是关键字)

流程控制

IO

输入

println 表示输出并换行

print() 普通输出

printf() 格式化输出

占位符格式与c基本一致

输出

import java.util.Scanner;//导入Scanner类

public class Main{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);//创建Scanner对象
        String name = scanner.nextLine(); //读取一行输入并获取字符串
        String age = Scanner.nextInt();   //读取一行输入并获取整数
    }
}

首先用import导入java.util.Scanner (必须放在源文件代码的开头)*

然后创建Scanner对象并传入System.in(标准输出流) (直接使用 System.in 更复杂)

不能再IDEA中在线运行,因为输入必须从命令行中读取

必须javac 文件名.java编译后

java 文件名 运行

if语句

if (条件) {
	//条件满足时执行的代码
}

只有一行代码时可省略花括号(极不推荐)

else语句

public class Main {
    public static void main(String[] args) {
        int n = 70;
        if (n >= 60) {
            System.out.println("及格了");
        } else {
            System.out.println("挂科了");
        }
        System.out.println("END");
    }
}

串联时注意顺序

一般从小到大 或 从大到小

if (n >= 90) {
    // n >= 90为true:
    System.out.println("优秀");
} else {
    // n >= 90为false:
    if (n >= 60) {
        // n >= 60为true:
        System.out.println("及格了");
    } else {
        // n >= 60为false:
        System.out.println("挂科了");
    }
}

比较条件时需注意浮点数的误差

public class Main {
    public static void main(String[] args) {
        double x = 1 - 9.0 / 10;
        if (Math.abs(x - 0.1) < 0.00001) {    //运用差值小于某极小值判断
            System.out.println("x is 0.1");
        } else {
            System.out.println("x is NOT 0.1");
        }
    }
}

判断引用类型相等

判断引用类型是否相等取决于 是否是同一对象

要判断引用内容是否相等 需使用equals()方法

public class Main {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "HELLO".toLowerCase();
        System.out.println(s1);
        System.out.println(s2);
        if (s1.equals(s2)) {
            System.out.println("s1 equals s2");
        } else {
            System.out.println("s1 not equals s2");
        }
    }
}

要避免s1为null报错NullPointerException

应使用短路运算符&&

或把不是null的对象放在前面

public class Main {
    public static void main(String[] args) {
        String s1 = null;
        if (s1 != null && s1.equals("hello")) {
            System.out.println("hello");
        }
    }
}

switch多重选择

除了if语句外,还有一种条件判断,是根据某个表达式的结果,分别去执行不同的分支。

例如,在游戏中,让用户选择选项:

  1. 单人模式
  2. 多人模式
  3. 退出游戏

这时,switch语句就派上用场了。

switch语句根据switch (表达式)计算的结果,跳转到匹配的case结果,然后继续执行后续语句,直到遇到break结束执行。

public class Main {
    public static void main(String[] args) {
        int option = 99;
        switch (option) {
        case 1:
            System.out.println("Selected 1");
            break;
        case 2:
            System.out.println("Selected 2");
            break;
        case 3:
            System.out.println("Selected 3");
            break;
        default:                                  //没有匹配到任何case时执行
            System.out.println("Not selected");
            break;
        }
    }
}

如果改为使用if语句实现…

if (option == 1) {
    System.out.println("Selected 1");
} else if (option == 2) {
    System.out.println("Selected 2");
} else if (option == 3) {
    System.out.println("Selected 3");
} else {
    System.out.println("Not selected");
}

切记不要忘记使用break

使用switch匹配字符串时,是比较内容相等 (不是对象)

switch语句支持枚举类型(但是我现在不会啊啊啊)

while循环

while的基本用法

while(条件表达式) {
	循环语句
}
//循环结束后继续执行其他代码
public class Main {
    public static void main(String[] args) {
        int sum = 0; // 累加的和,初始化为0
        int n = 1;
        while (n <= 100) { // 循环条件是n <= 100
            sum = sum + n; // 把n累加到sum中
            n ++; // n自身加1
        }
        System.out.println(sum); // 5050
    }
}

注意while先判断条件后循环(可能一次循环也没运行)

(累加for不比这好用?)

避免写死循环 (卡不死你)

do while循环

基本用法

do {
	先执行循环语句
} while (条件表达式)

与while的差别就是先运行一次再判定条件

###for循环

基本用法

for (初始条件; 循环检测条件; 循环后更新计数器) {
    // 执行语句
}

实例:对一个整型数组的所有元素求和

public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        int sum = 0;
        for (int i=0; i<ns.length; i++) {
            System.out.println("i = " + i + ", ns[i] = " + ns[i]);
            sum = sum + ns[i];
        }
        System.out.println("sum = " + sum);
    }
}

注意不要在语句中修改计数器

初始条件;循环检测条件;循环后更新计数器可以留空

for each循环

用于遍历数组

基本用法

int[] ns = { 1, 4, 9, 16, 25 };
for (int i=0; i<ns.length; i++) {
    System.out.println(ns[i]);
}
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int n : ns) {
            System.out.println(n);
        }
    }
}

小结(break&continue)

break语句可以跳出当前循环;

break语句通常配合if,在满足条件时提前结束整个循环;

break语句总是跳出最近的一层循环;

continue语句可以提前结束本次循环;

continue语句通常配合if,在满足条件时提前结束本次循环。

数组操作

遍历数组

for循环遍历数组,通过索引访问

public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int i=0; i<ns.length; i++) {
            int n = ns[i];
            System.out.println(n);
        }
    }
}

为了实现for循环遍历,初始条件为i=0,因为索引总是从0开始,继续循环的条件为i<ns.length,因为当i=ns.length时,i已经超出了索引范围(索引范围是0 ~ ns.length-1),每次循环后,i++

for each遍历数组,直接拿到数组中的元素,无法拿到索引

public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int n : ns) {
            System.out.println(n);
        }
    }
}

打印数组内容

  • 打印数组变量地址

    int[] ns = { 1, 1, 2, 3, 5, 8 };
    System.out.println(ns); // 类似 [I@7852e922
    
  • 打印数组中的元素内容(for each)

    int[] ns = { 1, 1, 2, 3, 5, 8 };
    for (int n : ns) {
        System.out.print(n + ", ");
    }
    
  • 使用java标准库中Arrays.toString()打印数组内容

    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int[] ns = { 1, 1, 2, 3, 5, 8 };
            System.out.println(Arrays.toString(ns));
        }
    }
    

数组排序

常用排序算法有

  • 冒泡排序
  • 插入排序
  • 快速排序

冒泡排序

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
        // 排序前:
        System.out.println(Arrays.toString(ns));
        for (int i = 0; i < ns.length - 1; i++) {
            for (int j = 0; j < ns.length - i - 1; j++) {
                if (ns[j] > ns[j+1]) {
                    // 交换ns[j]和ns[j+1]:
                    int tmp = ns[j];
                    ns[j] = ns[j+1];
                    ns[j+1] = tmp;
                }
            }
        }
        // 排序后:
        System.out.println(Arrays.toString(ns));
    }
}

冒泡排序的特点是,每一轮循环后,最大的一个数被交换到末尾,因此,下一轮循环就可以“刨除”最后的数,每一轮循环都比上一轮循环的结束位置靠前一位。

另外,注意到交换两个变量的值必须借助一个临时变量。

实际上数组本身已经被改变了

Arrays方法

快速排序(默认升序)

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
        Arrays.sort(ns);
        System.out.println(Arrays.toString(ns));
    }
}

多维数组

  • 二维数组

    二维数组就是数组的数组。定义一个二维数组如下:

public class Main {
    public static void main(String[] args) {
        int[][] ns = {
            { 1, 2, 3, 4 },
            { 5, 6, 7, 8 },
            { 9, 10, 11, 12 }
        };
        System.out.println(ns.length); // 3
    }
}

访问二维数组的某个元素需要使用array[row][col],例如:

System.out.println(ns[1][2]); // 7

打印数组

1.要打印一个二维数组,可以使用两层嵌套的for循环:

for (int[] arr : ns) {
    for (int n : arr) {
        System.out.print(n);
        System.out.print(', ');
    }
    System.out.println();
}

要使用多维数组中的元素也需要嵌套for循环

2.或者使用Java标准库的Arrays.deepToString()

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] ns = {
            { 1, 2, 3, 4 },
            { 5, 6, 7, 8 },
            { 9, 10, 11, 12 }
        };
        System.out.println(Arrays.deepToString(ns));
    }
}

  • 三位数组

    如果我们要访问三维数组的某个元素,例如,ns[2][0][1],只需要顺着定位找到对应的最终元素15即可。

    理论上,我们可以定义任意的N维数组。但在实际应用中,除了二维数组在某些时候还能用得上,更高维度的数组很少使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值