Java基础——常用API

一、Scanner类

简单使用

Scanner类的功能:实现键盘输入数据,到程序当中。

引用类型的一般步骤:
1.导包import 包路径。类名称;

如果使用的目标类,和当前类在同一个包下,则可以省略导包语句不写。

只有java.lang包下的内容不需要导包,其他的包都需要import语句。
2.创建

类名称 对象名 = new 类名称();

3.使用

对象名.成员方法名();

获取键盘输入的一个int数字:int num =src.nextInt();

获取键盘输入的一个字符串:String str =src.next();
示例:

public class Demo01Scanner {

public static void main(String[] args) {

        //2.创建

        //备注:System.in代表从键盘输入

        Scanner sc =new Scanner(System.in);

        //3.获取键盘输入的int数字

        int num = sc.nextInt();

        System.out.println("输入的是:" + num);

        //4.获取键盘输入的字符串

        String str = sc.next();

        System.out.println("输入的字符串是:" + str);

    }

}

练习例子

1.两数求和

题目:键盘输入两个int数字,并且求出和值
思路:
1.既然需要键盘输入,那么就要Scanner
2.Scanner的三个步骤:导包、创建、使用
3.需要两个数字,所以要调用两次nextInt方法
4.得到了两个数字,就需要加在一起5.打印输出

public class Demo02ScannerSum {

public static void main(String[] args) {

Scanner sc =new Scanner(System.in);

        System.out.println("请输入第一个数字:");

        int a = sc.nextInt();

        System.out.println("请输入第二个数字:");

        int b = sc.nextInt();

        int result = a + b;

        System.out.println("结果是:" + result);

    }

}

2.三数求最大值

public class Demo03ScannerMax {

public static void main(String[] args) {

Scanner sc =new Scanner(System.in);

        System.out.println("请输入第一个数字:");

        int a = sc.nextInt();

        System.out.println("请输入第二个数字:");

        int b = sc.nextInt();

        System.out.println("请输入第三个数字:");

        int c = sc.nextInt();

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

        System.out.println("最大值是:" + max);

    }

}

二、匿名对象

匿名对象

普通对象:
创建对象的标准格式:类名称 对象名 = new 类名称();
匿名对象就是只有右边的对象,没有左边的名字和赋值运算符。
注意事项:匿名对象只能使用唯一的一次,下次再使用不得不再创建一个新的对象
使用建议:如果确定有一个对象只需要使用唯一的一次,就可以使用匿名对象。
示例:

public class Demo01Anonymous {

public static void main(String[] args) {

//左边的one就是对象的名字

        Person one =new Person();

        one.name ="hello";

        one.showName();

        //匿名对象

        new Person().name="hi";

        new Person().showName();  //我叫null

    }

}

匿名对象作为参数和返回值

public class Demo02Anonymous {
public static void main(String[] args) {
        //普通使用方式
        //Scanner sc = new Scanner(System.in);
        //int num = sc.nextInt();
        //匿名对象的方式
        //int num =new Scanner(System.in).nextInt();
        //System.out.println("输入的是"+num);
        //使用一般写法传入参数
        //Scanner sc=new Scanner(System.in);
        //methodParam(sc);
        //使用匿名对象来进行传参
        //methodParam(new Scanner(System.in));
        methodParam(methodReturn());  //输出输入的数值

    }

        //匿名类作参数

    public static void methodParam(Scanner sc) {

          int num = sc.nextInt();

        System.out.println("输入的是:" + num);

    }

     //匿名类作返回值

    public static ScannermethodReturn() {

        //一般写法

        //Scanner sc= new Scanner(System.in);

        //return sc;

        //使用匿名对象

        return new Scanner(System.in);

    }

}

三、Random类

一、Random类

Random类用来生成随机数字。使用起来也是三个步骤:

  1. 导包
    import java.util.Random;
  2. 创建
    Random r = new Random(); // 小括号当中留空即可
  3. 使用
    获取一个随机的int数字(范围是int所有范围,有正负两种):int num = r.nextInt()
    获取一个随机的int数字(参数代表了范围,左闭右开区间):int num = r.nextInt(3)
    实际上代表的含义是:[0,3),也就是0~2
public class Demo01Random {

    public static void main(String[] args) {

        Random r = new Random();

        int num = r.nextInt();

        System.out.println("随机数是:" + num);

    }

}

二、Random中的nextIn用法(2)
1.无参

public class Demo02Random {

    public static void main(String[] args) {

        Random r = new Random();

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

            int num = r.nextInt(10); // 范围实际上是0~9

            System.out.println(num);

        }

    }

}

2.含参(含例子)
题目要求:
根据int变量n的值,来获取随机数字,范围是[1,n],可以取到1也可以取到n。
思路:

  1. 定义一个int变量n,随意赋值
  2. 要使用Random:三个步骤,导包、创建、使用
  3. 如果写10,那么就是09,然而想要的是110,可以发现:整体+1即可。
  4. 打印随机数字
public class Demo03Random {

    public static void main(String[] args) {

        int n = 5;

        Random r = new Random();

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

            // 本来范围是[0,n),整体+1之后变成了[1,n+1),也就是[1,n]

            int result = r.nextInt(n) + 1;

            System.out.println(result);

        }

    }

}

三、猜字小游戏
题目:
用代码模拟猜数字的小游戏。
思路:

  1. 首先需要产生一个随机数字,并且一旦产生不再变化。用Random的nextInt方法
  2. 需要键盘输入,所以用到了Scanner
  3. 获取键盘输入的数字,用Scanner当中的nextInt方法
  4. 已经得到了两个数字,判断(if)一下:
    如果太大了,提示太大,并且重试;
    如果太小了,提示太小,并且重试;
    如果猜中了,游戏结束。
  5. 重试就是再来一次,循环次数不确定,用while(true)。
public class Demo04RandomGame {

    public static void main(String[] args) {

        Random r = new Random();

        int randomNum = r.nextInt(100) + 1; // [1,100]

        Scanner sc = new Scanner(System.in);

        while (true) {

            System.out.println("请输入你猜测的数字:");

            int guessNum = sc.nextInt(); // 键盘输入猜测的数字

            if (guessNum > randomNum) {

                System.out.println("太大了,请重试。");

            } else if (guessNum < randomNum) {

                System.out.println("太小了,请重试。");

            } else {

                System.out.println("恭喜你,猜中啦!");

                break; // 如果猜中,不再重试

            }

        }

        System.out.println("游戏结束。");

    }

}

四、ArrayList集合

一、Array的不足
题目:
定义一个数组,用来存储3个Person对象。
数组有一个缺点:一旦创建,程序运行期间长度不可以发生改变。

public class Demo01Array {

    public static void main(String[] args) {

        // 首先创建一个长度为3的数组,里面用来存放Person类型的对象

        Person[] array = new Person[3];

        Person one = new Person("a", 8);

        Person two = new Person("b", 2);

        Person three = new Person("c", 3);

        // 将one当中的地址值赋值到数组的0号元素位置

        array[0] = one;

        array[1] = two;

        array[2] = three;

        System.out.println(array[0]); // 地址值

        System.out.println(array[1]); // 地址值

        System.out.println(array[2]); // 地址值

        System.out.println(array[1].getName()); // b

    }

}

二、ArrayList
数组的长度不可以发生改变。
但是ArrayList集合的长度是可以随意变化的。
对于ArrayList来说,有一个尖括号<E>代表泛型。
泛型:也就是装在集合当中的所有元素,全都是统一的什么类型。
注意:泛型只能是引用类型,不能是基本类型。
注意事项:
对于ArrayList集合来说,直接打印得到的不是地址值,而是内容。
如果内容是空,得到的是空的中括号:[]

public class Demo02ArrayList {

    public static void main(String[] args) {

        // 创建了一个ArrayList集合,集合的名称是list,里面装的全都是String字符串类型的数据

        // 备注:从JDK 1.7+开始,右侧的尖括号内部可以不写内容,但是<>本身还是要写的。

        ArrayList<String> list = new ArrayList<>();

        System.out.println(list); // []

        // 向集合当中添加一些数据,需要用到add方法。

        list.add("赵丽颖");

        System.out.println(list); // [赵丽颖]

        list.add("迪丽热巴");

        list.add("古力娜扎");

        list.add("玛尔扎哈");

        System.out.println(list); // [赵丽颖, 迪丽热巴, 古力娜扎, 玛尔扎哈]

//        list.add(100); // 错误写法!因为创建的时候尖括号泛型已经说了是字符串,添加进去的元素就必须都是字符串才行

    }

}

三、ArrayList常用方法
ArrayList当中的常用方法有:
public boolean add(E e):向集合当中添加元素,参数的类型和泛型一致。返回值代表添加是否成功。
备注:对于ArrayList集合来说,add添加动作一定是成功的,所以返回值可用可不用。
但是对于其他集合(今后学习)来说,add添加动作不一定成功。
public E get(int index):从集合当中获取元素,参数是索引编号,返回值就是对应位置的元素。
public E remove(int index):从集合当中删除元素,参数是索引编号,返回值就是被删除掉的元素。
public int size():获取集合的尺寸长度,返回值是集合中包含的元素个数。

public class Demo03ArrayListMethod {

    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<>();

        System.out.println(list); // []

        // 向集合中添加元素:add

        boolean success = list.add("0");

        System.out.println(list); // [0]

        System.out.println("添加的动作是否成功:" + success); // true

        list.add("1");

        list.add("2");

        list.add("3");

        list.add("4");

        System.out.println(list); // [0, 1, 2 3, 4]

        // 从集合中获取元素:get。索引值从0开始

        String name = list.get(2);

        System.out.println("第2号索引位置:" + name); 

        // 从集合中删除元素:remove。索引值从0开始。

        String whoRemoved = list.remove(3);

        System.out.println("被删除的人是:" + whoRemoved); // 3

        System.out.println(list); 

        // 获取集合的长度尺寸,也就是其中元素的个数

        int size = list.size();

        System.out.println("集合的长度是:" + size);

    }

}

四、集合遍历

public class Demo04ArrayListEach {

    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<>();

        list.add("1");

        list.add("2");

        list.add("3");

        // 遍历集合

        for (int i = 0; i < list.size(); i++) {

            System.out.println(list.get(i));

        }

    }

}

五、ArrayList存储基本数据
如果希望向集合ArrayList当中存储基本类型数据,必须使用基本类型对应的“包装类”。
基本类型 包装类(引用类型,包装类都位于java.lang包下)
byte Byte
short Short
int Integer 【特殊】
long Long
float Float
double Double
char Character 【特殊】
boolean Boolean
从JDK 1.5+开始,支持自动装箱、自动拆箱。
自动装箱:基本类型 --> 包装类型
自动拆箱:包装类型 --> 基本类型

public class Demo05ArrayListBasic {

    public static void main(String[] args) {

        ArrayList<String> listA = new ArrayList<>();

        // 错误写法!泛型只能是引用类型,不能是基本类型

//        ArrayList<int> listB = new ArrayList<>();

        ArrayList<Integer> listC = new ArrayList<>();

        listC.add(100);

        listC.add(200);

        System.out.println(listC); // [100, 200]

        int num = listC.get(1);

        System.out.println("第1号元素是:" + num);

    }

}

六、ArrayList练习题
1.例题一
题目:
生成6个1~33之间的随机整数,添加到集合,并遍历集合。
思路:

  1. 需要存储6个数字,创建一个集合,<Integer>
  2. 产生随机数,需要用到Random
  3. 用循环6次,来产生6个随机数字:for循环
  4. 循环内调用r.nextInt(int n),参数是33,032,整体+1才是133
  5. 把数字添加到集合中:add
  6. 遍历集合:for、size、get
public class Demo01ArrayListRandom {

    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<>();

        Random r = new Random();

        for (int i = 0; i < 6; i++) {

            int num = r.nextInt(33) + 1;

            list.add(num);

        }

        // 遍历集合

        for (int i = 0; i < list.size(); i++) {

            System.out.println(list.get(i));

        }

    }

}

2.例题二
题目:
自定义4个学生对象,添加到集合,并遍历。
思路:

  1. 自定义Student学生类,四个部分。
  2. 创建一个集合,用来存储学生对象。泛型:<Student>
  3. 根据类,创建4个学生对象。
  4. 将4个学生对象添加到集合中:add
  5. 遍历集合:for、size、get
public class Demo02ArrayListStudent {

    public static void main(String[] args) {

        ArrayList<Student> list = new ArrayList<>();

        Student one = new Student("洪七公", 20);

        Student two = new Student("欧阳锋", 21);

        Student three = new Student("黄药师", 22);

        Student four = new Student("段智兴", 23);

        list.add(one);

        list.add(two);

        list.add(three);

        list.add(four);

        // 遍历集合

        for (int i = 0; i < list.size(); i++) {

            Student stu = list.get(i);

            System.out.println("姓名:" + stu.getName() + ",年龄" + stu.getAge());

        }

    }

}

3.例题三
题目:
定义以指定格式打印集合的方法(ArrayList类型作为参数),使用{}扩起集合,使用@分隔每个元素。
格式参照 {元素@元素@元素}。
System.out.println(list); [10, 20, 30]
printArrayList(list); {10@20@30}

public class Demo03ArrayListPrint {

    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<>();

        list.add("张三丰");

        list.add("宋远桥");

        list.add("张无忌");

        list.add("张翠山");

        System.out.println(list); // [张三丰, 宋远桥, 张无忌, 张翠山]

        printArrayList(list);

    }

    /*

    定义方法的三要素

    返回值类型:只是进行打印而已,没有运算,没有结果;所以用void

    方法名称:printArrayList

    参数列表:ArrayList

    */

    public static void printArrayList(ArrayList<String> list) {

        // {10@20@30}

        System.out.print("{");

        for (int i = 0; i < list.size(); i++) {

            String name = list.get(i);

            if (i == list.size() - 1) {

                System.out.println(name + "}");

            } else {

                System.out.print(name + "@");

            }

        }

    }

}

4.例题四
题目:
用一个大集合存入20个随机数字,然后筛选其中的偶数元素,放到小集合当中。
要求使用自定义的方法来实现筛选。
分析:

  1. 需要创建一个大集合,用来存储int数字:<Integer>
  2. 随机数字就用Random nextInt
  3. 循环20次,把随机数字放入大集合:for循环、add方法
  4. 定义一个方法,用来进行筛选。
    筛选:根据大集合,筛选符合要求的元素,得到小集合。
    三要素
    返回值类型:ArrayList小集合(里面元素个数不确定)
    方法名称:getSmallList
    参数列表:ArrayList大集合(装着20个随机数字)
  5. 判断(if)是偶数:num % 2 == 0
  6. 如果是偶数,就放到小集合当中,否则不放。
public class Demo04ArrayListReturn {

    public static void main(String[] args) {

        ArrayList<Integer> bigList = new ArrayList<>();

        Random r = new Random();

        for (int i = 0; i < 20; i++) {

            int num = r.nextInt(100) + 1; // 1~100

            bigList.add(num);

        }

        ArrayList<Integer> smallList = getSmallList(bigList);

        System.out.println("偶数总共有多少个:" + smallList.size());

        for (int i = 0; i < smallList.size(); i++) {

            System.out.println(smallList.get(i));

        }

    }

    // 这个方法,接收大集合参数,返回小集合结果

    public static ArrayList<Integer> getSmallList(ArrayList<Integer> bigList) {

        // 创建一个小集合,用来装偶数结果

        ArrayList<Integer> smallList = new ArrayList<>();

        for (int i = 0; i < bigList.size(); i++) {

            int num = bigList.get(i);

            if (num % 2 == 0) {

                smallList.add(num);

            }

        }

        return smallList;

    }

}

五、String类

一、String基础
java.lang.String类代表字符串。API当中说:Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例实现。
其实就是说:程序当中所有的双引号字符串,都是String类的对象。(就算没有new,也照样是。)

字符串的特点:

  1. 字符串的内容永不可变。【重点】
  2. 正是因为字符串不可改变,所以字符串是可以共享使用的。
  3. 字符串效果上相当于是char[]字符数组,但是底层原理是byte[]字节数组。

创建字符串的常见3+1种方式。
三种构造方法:
public String():创建一个空白字符串,不含有任何内容。
public String(char[] array):根据字符数组的内容,来创建对应的字符串。
public String(byte[] array):根据字节数组的内容,来创建对应的字符串。
一种直接创建:String str = "Hello"; // 右边直接用双引号
注意:直接写上双引号,就是字符串对象。

public class Demo01String {

public static void main(String[] args) {

// 使用空参构造

        String str1 =new String(); // 小括号留空,说明字符串什么内容都没有。

        System.out.println("第1个字符串:" + str1);

        // 根据字符数组创建字符串

        char[] charArray = {'A', 'B', 'C'};

        String str2 =new String(charArray);

        System.out.println("第2个字符串:" + str2);

        // 根据字节数组创建字符串

        byte[] byteArray = {97, 98, 99};

        String str3 =new String(byteArray);

        System.out.println("第3个字符串:" + str3);

        // 直接创建

        String str4 ="Hello";

        System.out.println("第4个字符串:" + str4);

    }

}

二、字符串常量池
字符串常量池:程序当中直接写上的双引号字符串,就在字符串常量池中。
对于基本类型来说,==是进行数值的比较。
对于引用类型来说,==是进行【地址值】的比较。

public class Demo02StringPool {

public static void main(String[] args) {

        String str1 ="abc";

        String str2 ="abc";

        char[] charArray = {'a', 'b', 'c'};

        String str3 =new String(charArray);

        System.out.println(str1 == str2); // true

        System.out.println(str1 == str3); // false

        System.out.println(str2 == str3); // false

    }

}

三、字符串的比较
==是进行对象的地址值比较,如果确实需要字符串的内容比较,可以使用两个方法:public boolean equals(Object obj):参数可以是任何对象,只有参数是一个字符串并且内容相同的才会给true;否则返回false。
注意事项:
1. 任何对象都能用Object进行接收。
2. equals方法具有对称性,也就是a.equals(b)和b.equals(a)效果一样。
3. 如果比较双方一个常量一个变量,推荐把常量字符串写在前面。
推荐:"abc".equals(str) 不推荐:str.equals("abc")
public boolean equalsIgnoreCase(String str):忽略大小写,进行内容比较。

public class Demo01StringEquals {

public static void main(String[] args) {

        String str1 ="Hello";

        String str2 ="Hello";

        char[] charArray = {'H', 'e', 'l', 'l', 'o'};

        String str3 =new String(charArray);

        System.out.println(str1.equals(str2)); // true

        System.out.println(str2.equals(str3)); // true

        System.out.println(str3.equals("Hello")); // true

        System.out.println("Hello".equals(str1)); // true

        String str4 ="hello";

        System.out.println(str1.equals(str4)); // false

        System.out.println("=================");

        String str5 =null;

        System.out.println("abc".equals(str5)); // 推荐:false

//        System.out.println(str5.equals("abc")); // 不推荐:报错,空指针异常NullPointerException

        System.out.println("=================");

        String strA ="Java";

        String strB ="java";

        System.out.println(strA.equals(strB)); // false,严格区分大小写

        System.out.println(strA.equalsIgnoreCase(strB)); // true,忽略大小写

        // 注意,只有英文字母区分大小写,其他都不区分大小写

        System.out.println("abc一123".equalsIgnoreCase("abc壹123")); // false

    }

}

四、String获取相关方法
String当中与获取相关的常用方法有:public int length():获取字符串当中含有的字符个数,拿到字符串长度。public String concat(String str):将当前字符串和参数字符串拼接成为返回值新的字符串。public char charAt(int index):获取指定索引位置的单个字符。(索引从0开始。)public int indexOf(String str):查找参数字符串在本字符串当中首次出现的索引位置,如果没有返回-1值。

public class Demo02StringGet {

public static void main(String[] args) {

// 获取字符串的长度

        int length ="asdasfeutrvauevbueyvb".length();

        System.out.println("字符串的长度是:" + length);

        // 拼接字符串

        String str1 ="Hello";

        String str2 ="World";

        String str3 = str1.concat(str2);

        System.out.println(str1); // Hello,原封不动

        System.out.println(str2); // World,原封不动

        System.out.println(str3); // HelloWorld,新的字符串

        System.out.println("==============");

        // 获取指定索引位置的单个字符

        char ch ="Hello".charAt(1);

        System.out.println("在1号索引位置的字符是:" + ch);

        System.out.println("==============");

        // 查找参数字符串在本来字符串当中出现的第一次索引位置

        // 如果根本没有,返回-1值

        String original ="HelloWorldHelloWorld";

        int index = original.indexOf("llo");

        System.out.println("第一次索引值是:" + index); // 2

        System.out.println("HelloWorld".indexOf("abc")); // -1

    }

}

五、String的截取方法
字符串的截取方法:
public String substring(int index):截取从参数位置一直到字符串末尾,返回新字符串。
public String substring(int begin, int end):截取从begin开始,一直到end结束,中间的字符串。
备注:[begin,end),包含左边,不包含右边。

public class Demo03Substring {

public static void main(String[] args) {

String str1 ="HelloWorld";

        String str2 = str1.substring(5);

        System.out.println(str1); // HelloWorld,原封不动

        System.out.println(str2); // World,新字符串

        System.out.println("================");

        String str3 = str1.substring(4, 7);

        System.out.println(str3); // oWo

        System.out.println("================");

        // 下面这种写法,字符串的内容仍然是没有改变的

        // 下面有两个字符串:"Hello","Java"

        // strA当中保存的是地址值。

        // 本来地址值是Hello的0x666,

        // 后来地址值变成了Java的0x999

        String strA ="Hello";

        System.out.println(strA); // Hello

        strA ="Java";

        System.out.println(strA); // Java

    }

}

六、String的转换相关方法
String当中与转换相关的常用方法有:
public char[] toCharArray():将当前字符串拆分成为字符数组作为返回值。
public byte[] getBytes():获得当前字符串底层的字节数组。
public String replace(CharSequence oldString, CharSequence newString):
将所有出现的老字符串替换成为新的字符串,返回替换之后的结果新字符串。
备注:CharSequence意思就是说可以接受字符串类型。

public class Demo04StringConvert {

public static void main(String[] args) {

// 转换成为字符数组

        char[] chars ="Hello".toCharArray();

        System.out.println(chars[0]); // H

        System.out.println(chars.length); // 5

        System.out.println("==============");

        // 转换成为字节数组

        byte[] bytes ="abc".getBytes();

        for (int i =0; i < bytes.length; i++) {

System.out.println(bytes[i]);

        }

System.out.println("==============");

        // 字符串的内容替换

        String str1 ="How do you do?";

        String str2 = str1.replace("o", "*");

        System.out.println(str1); // How do you do?

        System.out.println(str2); // H*w d* y*u d*?

        System.out.println("==============");

        String lang1 ="会不会玩儿呀!你大爷的!你大爷的!你大爷的!!!";

        String lang2 = lang1.replace("你大爷的", "****");

        System.out.println(lang2); // 会不会玩儿呀!****!****!****!!!

    }

}

七、String的分割方法
分割字符串的方法:public String[] split(String regex):按照参数的规则,将字符串切分成为若干部分。
注意事项:split方法的参数其实是一个“正则表达式”,今后学习。
今天要注意:如果按照英文句点“.”进行切分,必须写"\."(两个反斜杠)

public class Demo05StringSplit {

public static void main(String[] args) {

String str1 ="aaa,bbb,ccc";

        String[] array1 = str1.split(",");

        for (int i =0; i < array1.length; i++) {

System.out.println(array1[i]);

        }

System.out.println("===============");

        String str2 ="aaa bbb ccc";

        String[] array2 = str2.split(" ");

        for (int i =0; i < array2.length; i++) {

System.out.println(array2[i]);

        }

System.out.println("===============");

        String str3 ="XXX.YYY.ZZZ";

        String[] array3 = str3.split("\\.");

        System.out.println(array3.length); // 0

        for (int i =0; i < array3.length; i++) {

System.out.println(array3[i]);

        }

}

}

八、练习题
1.按指定格式拼接字符
题目:
定义一个方法,把数组{1,2,3}按照指定格式拼接成一个字符串。格式参照如下:[word1#word2#word3]。
分析:1. 首先准备一个int[]数组,内容是:1、2、3

  1. 定义一个方法,用来将数组变成字符串
    三要素
    返回值类型:String
    方法名称:fromArrayToString
    参数列表:int[]
  2. 格式:[word1#word2#word3]
    用到:for循环、字符串拼接、每个数组元素之前都有一个word字样、分隔使用的是#、区分一下是不是最后一个4. 调用方法,得到返回值,并打印结果字符串*/
public class Demo06StringPractise {

public static void main(String[] args) {

int[] array = {1, 2, 3, 4};

        String result =fromArrayToString(array);

        System.out.println(result);

    }

public static StringfromArrayToString(int[] array) {

String str ="[";

        for (int i =0; i < array.length; i++) {

if (i == array.length -1) {

str +="word" + array[i] +"]";

            }else {

str +="word" + array[i] +"#";

            }

}

return str;

    }

}

2.统计输入的字符串
题目:
键盘输入一个字符串,并且统计其中各种字符出现的次数。
种类有:大写字母、小写字母、数字、其他
思路:

  1. 既然用到键盘输入,肯定是Scanner
  2. 键盘输入的是字符串,那么:String str = sc.next();
  3. 定义四个变量,分别代表四种字符各自的出现次数。4. 需要对字符串一个字、一个字检查,String-->char[],方法就是toCharArray()
  4. 遍历char[]字符数组,对当前字符的种类进行判断,并且用四个变量进行++动作。6. 打印输出四个变量,分别代表四种字符出现次数。
public class Demo07StringCount {

public static void main(String[] args) {

Scanner sc =new Scanner(System.in);

        System.out.println("请输入一个字符串:");

        String input = sc.next(); // 获取键盘输入的一个字符串

        int countUpper =0; // 大写字母

        int countLower =0; // 小写字母

        int countNumber =0; // 数字

        int countOther =0; // 其他字符

        char[] charArray = input.toCharArray();

        for (int i =0; i < charArray.length; i++) {

char ch = charArray[i]; // 当前单个字符

            if ('A' <= ch && ch <='Z') {

countUpper++;

            }else if ('a' <= ch && ch <='z') {

countLower++;

            }else if ('0' <= ch && ch <='9') {

countNumber++;

            }else {

countOther++;

            }

}

System.out.println("大写字母有:" + countUpper);

        System.out.println("小写字母有:" + countLower);

        System.out.println("数字有:" + countNumber);

        System.out.println("其他字符有:" + countOther);

    }

}

六、static静态

一、静态static修饰成员变量
学生类:

public class Student {

private int id; // 学号

    private Stringname; // 姓名

    private int age; // 年龄

    static Stringroom; // 所在教室

    private static int idCounter =0; // 学号计数器,每当new了一个新对象的时候,计数器++

    public Student() {

this.id = ++idCounter;

    }

public Student(String name, int age) {

this.name = name;

        this.age = age;

        this.id = ++idCounter;

    }

public int getId() {

return id;

    }

public void setId(int id) {

this.id = id;

    }

public StringgetName() {

return name;

    }

public void setName(String name) {

this.name = name;

    }

public int getAge() {

return age;

    }

public void setAge(int age) {

this.age = age;

    }

}

如果一个成员变量使用了static关键字,那么这个变量不再属于对象自己,而是属于所在的类。多个对象共享同一份数据。

public class Demo01StaticField {

public static void main(String[] args) {

Student two =new Student("黄蓉", 16);

        two.room ="101教室";

        System.out.println("姓名:" + two.getName()

+",年龄:" + two.getAge() +",教室:" + two.room

                +",学号:" + two.getId());

        Student one =new Student("郭靖", 19);

        System.out.println("姓名:" + one.getName()

+",年龄:" + one.getAge() +",教室:" + one.room

                +",学号:" + one.getId());

    }

}

二、静态static修饰成员方法
MyClass类:

public class MyClass {

int num; // 成员变量

    static int numStatic; // 静态变量

    // 成员方法

    public void method() {

System.out.println("这是一个成员方法。");

        // 成员方法可以访问成员变量

        System.out.println(num);

        // 成员方法可以访问静态变量

        System.out.println(numStatic);

    }

// 静态方法

    public static void methodStatic() {

System.out.println("这是一个静态方法。");

        // 静态方法可以访问静态变量

        System.out.println(numStatic);

        // 静态不能直接访问非静态【重点】

//        System.out.println(num); // 错误写法!

        // 静态方法中不能使用this关键字。

//        System.out.println(this); // 错误写法!

    }

}

一旦使用static修饰成员方法,那么这就成为了静态方法。静态方法不属于对象,而是属于类的。
如果没有static关键字,那么必须首先创建对象,然后通过对象才能使用它。
如果有了static关键字,那么不需要创建对象,直接就能通过类名称来使用它。
无论是成员变量,还是成员方法。如果有了static,都推荐使用类名称进行调用。
静态变量:类名称.静态变量
静态方法:类名称.静态方法()
注意事项:

  1. 静态不能直接访问非静态。
    原因:因为在内存当中是【先】有的静态内容,【后】有的非静态内容。“先人不知道后人,但是后人知道先人。”
  2. 静态方法当中不能用this。
    原因:this代表当前对象,通过谁调用的方法,谁就是当前对象。*/
public class Demo02StaticMethod {

public static void main(String[] args) {

MyClass obj =new MyClass(); // 首先创建对象

        // 然后才能使用没有static关键字的内容

        obj.method();

        // 对于静态方法来说,可以通过对象名进行调用,也可以直接通过类名称来调用。

        obj.methodStatic(); // 正确,不推荐,这种写法在编译之后也会被javac翻译成为“类名称.静态方法名”

        MyClass.methodStatic(); // 正确,推荐

        // 对于本类当中的静态方法,可以省略类名称

        myMethod();

        Demo02StaticMethod.myMethod(); // 完全等效

    }

public static void myMethod() {

System.out.println("自己的方法!");

    }

}

三、静态代码块
Person类:

public class Person {

static {

System.out.println("静态代码块执行!");

    }

public Person() {

System.out.println("构造方法执行!");

    }

}

静态代码块的格式是:public class 类名称{

static {

    // 静态代码块的内容}

}

特点:当第一次用到本类时,静态代码块执行唯一的一次。

静态内容总是优先于非静态,所以静态代码块比构造方法先执行。

静态代码块的典型用途:

用来一次性地对静态成员变量进行赋值。

public class Demo04Static {

public static void main(String[] args) {

Person one =new Person();

        Person two =new Person();

    }

}

七、Arrays工具类

一、Arrays基础
java.util.Arrays是一个与数组相关的工具类,里面提供了大量静态方法,用来实现数组常见的操作。
public static String toString(数组):将参数数组变成字符串(按照默认格式:[元素1, 元素2, 元素3...])
public static void sort(数组):按照默认升序(从小到大)对数组的元素进行排序。
备注:

  1. 如果是数值,sort默认按照升序从小到大
  2. 如果是字符串,sort默认按照字母升序
  3. 如果是自定义的类型,那么这个自定义的类需要有Comparable或者Comparator接口的支持。(今后学习)
public class Demo01Arrays {

public static void main(String[] args) {

int[] intArray = {10, 20, 30};

        // 将int[]数组按照默认格式变成字符串

        String intStr = Arrays.toString(intArray);

        System.out.println(intStr); // [10, 20, 30]

        int[] array1 = {2, 1, 3, 10, 6};

        Arrays.sort(array1);

        System.out.println(Arrays.toString(array1)); // [1, 2, 3, 6, 10]

        String[] array2 = {"bbb", "aaa", "ccc"};

        Arrays.sort(array2);

        System.out.println(Arrays.toString(array2)); // [aaa, bbb, ccc]

    }

}

二、Arrays练习
题目:
请使用Arrays相关的API,将一个随机字符串中的所有字符升序排列,并倒序打印。

public class Demo02ArraysPractise {

public static void main(String[] args) {

String str ="asv76agfqwdfvasdfvjh";

        // 如何进行升序排列:sort

        // 必须是一个数组,才能用Arrays.sort方法

        // String --> 数组,用toCharArray

        char[] chars = str.toCharArray();

        Arrays.sort(chars); // 对字符数组进行升序排列

        // 需要倒序遍历

        for (int i = chars.length -1; i >=0; i--) {

System.out.println(chars[i]);

        }

}

}

八、Math类

一、Math基础
java.util.Math类是数学相关的工具类,里面提供了大量的静态方法,完成与数学运算相关的操作。

public static double abs(double num):获取绝对值。有多种重载。

public static double ceil(double num):向上取整。

public static double floor(double num):向下取整。

public static long round(double num):四舍五入。

Math.PI代表近似的圆周率常量(double)。*/

public class Demo03Math {

public static void main(String[] args) {

// 获取绝对值

        System.out.println(Math.abs(3.14)); // 3.14

        System.out.println(Math.abs(0)); // 0

        System.out.println(Math.abs(-2.5)); // 2.5

        System.out.println("================");

        // 向上取整

        System.out.println(Math.ceil(3.9)); // 4.0

        System.out.println(Math.ceil(3.1)); // 4.0

        System.out.println(Math.ceil(3.0)); // 3.0

        System.out.println("================");

        // 向下取整,抹零

        System.out.println(Math.floor(30.1)); // 30.0

        System.out.println(Math.floor(30.9)); // 30.0

        System.out.println(Math.floor(31.0)); // 31.0

        System.out.println("================");

        System.out.println(Math.round(20.4)); // 20

        System.out.println(Math.round(10.5)); // 11

    }

}

二、Math练习题
题目:
计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个?
分析:

  1. 既然已经确定了范围,for循环2. 起点位置-10.8应该转换成为-10,
    两种办法:
    2.1 可以使用Math.ceil方法,向上(向正方向)取整 2.2 强转成为int,自动舍弃所有小数位
  2. 每一个数字都是整数,所以步进表达式应该是num++,这样每次都是+1的。
  3. 如何拿到绝对值:Math.abs方法。
  4. 一旦发现了一个数字,需要让计数器++进行统计。
    备注:如果使用Math.ceil方法,-10.8可以变成-10.0。注意double也是可以进行++的。
public class Demo04MathPractise {

public static void main(String[] args) {

int count =0; // 符合要求的数量

        double min = -10.8;

        double max =5.9;

        // 这样处理,变量i就是区间之内所有的整数

        for (int i = (int) min; i < max; i++) {

int abs = Math.abs(i); // 绝对值

            if (abs >6 || abs <2.1) {

System.out.println(i);

                count++;

            }

}

System.out.println("总共有:" + count); // 9

    }

}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,366评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,521评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,689评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,925评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,942评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,727评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,447评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,349评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,820评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,990评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,127评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,812评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,471评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,017评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,142评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,388评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,066评论 2 355