Java学习 day7 (常用API)Scanner类.Random类.Arraylist类

前言:

今天我们进行了常用API的学习,所谓API其实就是应用程序编程接口,其实说白了就是一个个大佬们把现成的写好的功能封装了起来,方便了我们的调用和使用。


今日重点:

  1. API概述
  2. scanner类(文本扫描)
  3. random类(随机数)
  4. ArrayList(对象数组)

API

概述:

API(Application Programming Interface),应用程序编程接口。Java API是一本程序员的 字典  ,是JDK中提供给我们使用的类的说明文档。这些类将底层的代码实现封装了起来,我们不需要关心这些类是如何实现的,只需要学习这些类如何使用即可。所以我们可以通过查询API的方式,来学习Java提供的类,并得知如何使用它们。

API使用步骤

1. 打开帮助文档。

2. 点击显示,找到索引,看到输入框。

3. 你要找谁?在输入框里输入,然后回车。

4. 看包。java.lang下的类不需要导包,其他需要。

5. 看类的解释和说明。

6. 学习构造方法。

7. 使用成员方法。


Scanner类

Scanner类是一个可以解析基本类型和字符串的简单文本扫描器(有点类似于Python中的input)。 例如,以下代码使用户能够从 System.in 中读取一个数:

Scanner  sc  = new  Scanner(System.in);
int  i  = sc.nextInt();

System.in 系统输入指的是通过键盘录入数据。

引用类型的一般使用步骤:

1. 导包
import 包路径.类名称;
如果需要使用的目标类,和当前类位于同一个包下,则可以省略导包语句不写。
只有java.lang包下的内容不需要导包,其他的包都需要import语句。

2. 创建
类名称 对象名 = new 类名称();
3. 使用
对象名.成员方法名()
获取键盘输入的一个int数字:int num = sc.nextInt();
获取键盘输入的一个字符串:String str = sc.next();

scanner使用步骤:

import java.util.Scanner; // 1. 导包

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


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("输入的int数字是:" + num);

        // 4. 获取键盘输入的字符串
        String str = sc.next();
        System.out.println("输入的字符串是:" + str);
    }

}

小练习(求和):

import java.util.Scanner;

/*
题目:
键盘输入两个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);
    }

}

小练习:(取最大值) 

import java.util.Scanner;

/*
题目:
键盘输入三个int数字,然后求出其中的最大值。

思路:
1. 既然是键盘输入,肯定需要用到Scanner
2. Scanner三个步骤:导包、创建、使用nextInt()方法
3. 既然是三个数字,那么调用三次nextInt()方法,得到三个int变量
4. 无法同时判断三个数字谁最大,应该转换成为两个步骤:
    4.1 首先判断前两个当中谁最大,拿到前两个的最大值
    4.2 拿着前两个中的最大值,再和第三个数字比较,得到三个数字当中的最大值
5. 打印最终结果
 */
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 temp = a > b ? a : b;
        int max = temp > c ? temp : c;
        System.out.println("最大值是:" + max);
    }

}

匿名对象

匿名对象是指,创建对象时,只有创建对象的语句,却没有把对象地址值赋值给某个变量。虽然是创建对象的简化写法,但是应用场景非常有限。(说白了就是省略了起名字的这个步骤)

匿名对象  :没有变量名的对象。

创建对象的标准格式:
类名称 对象名 = new 类名称();

匿名对象就是只有右边的对象,没有左边的名字和赋值运算符。
new 类名称();

注意事项:匿名对象只能使用唯一的一次,下次再用不得不再创建一个新对象。
使用建议:如果确定有一个对象只需要使用唯一的一次,就可以用匿名对象。
public class Person {

    String name;

    public void showName() {
        System.out.println("我叫:" + name);
    }

}
public class Demo01Anonymous {

    public static void main(String[] args) {
        // 左边的one就是对象的名字
        Person one = new Person();
        one.name = "高圆圆";
        one.showName(); // 我叫高圆圆
        System.out.println("===============");

        // 匿名对象
        new Person().name = "赵又廷";
        new Person().showName(); // 我叫:null
    }

}

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

import java.util.Scanner;

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));

        Scanner sc = methodReturn();
        int num = sc.nextInt();
        System.out.println("输入的是:" + num);
    }

    public static void methodParam(Scanner sc) {
        int num = sc.nextInt();
        System.out.println("输入的是:" + num);
    }

    public static Scanner methodReturn() {
//普通方式
//        Scanner sc = new Scanner(System.in);
//        return sc;
//匿名对象作为方法返回值
        return new Scanner(System.in);
    }

}

Random

random类用于生成随机数,在Python中也有同名类,功能一样,不过语法不太一样。

random类的使用也跟常用步骤一样,有三个步骤!

import java.util.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);
    }

}

需要注意的是随机数生成跟数组一样,是短一个的,如果写10,实际范围是0-10!

import java.util.Random;

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);
        }
    }

}

小练习:(获取随机数)

import java.util.Random;

/*
题目要求:
根据int变量n的值,来获取随机数字,范围是[1,n],可以取到1也可以取到n。

思路:
1. 定义一个int变量n,随意赋值
2. 要使用Random:三个步骤,导包、创建、使用
3. 如果写10,那么就是0~9,然而想要的是1~10,可以发现:整体+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);
        }

    }

}

小练习:(猜数字小游戏)

import java.util.Random;
import java.util.Scanner;

/*
题目:
用代码模拟猜数字的小游戏。

思路:
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

之前我们学习过数组,他有一个缺点就是一旦创建,程序运行期间长度不可以发生改变。

首先创建一个标准类: 

public class Person {

    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 再创建一个普通数组:

public class Demo01Array {

    public static void main(String[] args) {
        // 首先创建一个长度为3的数组,里面用来存放Person类型的对象
        Person[] array = new Person[3];

        Person one = new Person("迪丽热巴", 18);
        Person two = new Person("古力娜扎", 28);
        Person three = new Person("玛尔扎哈", 38);

        // 将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()); // 古力娜扎
    }

}

为了解决这个问题,Java提供了另一个容器 java.util.ArrayList  集合类,让我们可以更便捷的存储和操作对象数据。

对象数组:

import java.util.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常用方法:

import java.util.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("柳岩");
        System.out.println(list); // [柳岩]
        System.out.println("添加的动作是否成功:" + success); // true

        list.add("高圆圆");
        list.add("赵又廷");
        list.add("李小璐");
        list.add("贾乃亮");
        System.out.println(list); // [柳岩, 高圆圆, 赵又廷, 李小璐, 贾乃亮]

        // 从集合中获取元素:get。索引值从0开始
        String name = list.get(2);
        System.out.println("第2号索引位置:" + name); // 赵又廷

        // 从集合中删除元素:remove。索引值从0开始。
        String whoRemoved = list.remove(3);
        System.out.println("被删除的人是:" + whoRemoved); // 李小璐
        System.out.println(list); // [柳岩, 高圆圆, 赵又廷, 贾乃亮]

        // 获取集合的长度尺寸,也就是其中元素的个数
        int size = list.size();
        System.out.println("集合的长度是:" + size);
    }

}

遍历集合:

import java.util.ArrayList;

public class Demo04ArrayListEach {

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("迪丽热巴");
        list.add("古力娜扎");
        list.add("玛尔扎哈");

        // 遍历集合
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }

}

包装类:

由于对象集合无法储存基本数据类型,所以要是想让他储存的话,可以对他进行包装!!

如果希望向集合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);
    }

}

 小练习:

import java.util.ArrayList;
import java.util.Random;

/*
题目:
生成6个1~33之间的随机整数,添加到集合,并遍历集合。

思路:
1. 需要存储6个数字,创建一个集合,<Integer>
2. 产生随机数,需要用到Random
3. 用循环6次,来产生6个随机数字:for循环
4. 循环内调用r.nextInt(int n),参数是33,0~32,整体+1才是1~33
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));
        }
    }

}

 小练习二:

public class Student {

    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
import java.util.ArrayList;

/*
题目:
自定义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());
        }
    }

}

 

import java.util.ArrayList;

/*
题目:
定义以指定格式打印集合的方法(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 + "@");
            }
        }
    }

}
import java.util.ArrayList;
import java.util.Random;

/*
题目:
用一个大集合存入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;
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Andy393939

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值