day07_Scanner类、Random类、ArrayList 类

API

概述

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

API使用步骤

  1. 打开帮助文档。
  2. 点击显示,找到索引,看到输入框。
  3. 你要找谁?在输入框里输入,然后回车。
  4. 看包。java.lang下的类不需要导包,其他需要。
  5. 看类的解释和说明。
  6. 学习构造方法
  7. 使用成员方法/变量

引用类型使用步骤

类属于引用类型中的一种,所以去使用步骤符合引用类型的使用步骤。

1:导包

使用import关键字导包,在类的所有代码之前导包,引入要使用的类型,java.lang包下的所有类无需导入。

格式:

2:创建对象

使用该类的构造方法,创建一个该类的对象。 格式:

3:调用方法

调用该类的成员方法,完成指定功能。 格式:

// 接收一个键盘录入的整数
int i = sc.nextInt();

Scanner类 

Scanner使用步骤

查看类
  • java.util.Scanner :该类需要import导入后使用。
查看构造方法
  • public Scanner(InputStream source) : 构造一个新的 Scanner ,它生成的值是从指定的输入流扫描的。
查看成员方法
  • public int nextInt() :将输入信息的下一个标记扫描为一个 int 值。
  • public String next():将输入信息的下一个标记扫描为一个 String值。

举例

package demo01;



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

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


获取键盘输入的一个int数字:int num = sc.nextInt();
获取键盘输入的一个字符串:String str = sc.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("输入的int数字是:" + num);

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

}

使用Scanner类,完成接收键盘录入三个数据并获取最大值,代码如下

package demo01;


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 Scanner(System.in).nextInt();
  • 匿名对象可以作为方法的参数
public class Demo01Anonymous {

    public static void main(String[] args) {
        /*
         普通方式
         Scanner sc = new Scanner(System.in);
         input(sc);
          */

        //匿名对象作为方法接收的参数
        input(new Scanner(System.in));
    }

    public static void input(Scanner sc) {
        System.out.println(sc);
    }
}
  • 匿名对象可以作为方法的返回值
public class Demo01Anonymous {
    
    public static void main(String[] args) {
        Scanner sc = getScanner();
    }

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

    }
}

注意事项:

  • 匿名对象只能使用唯一的一次,下次再用不得不再创建一个新对象。

使用建议:

  • 如果确定有一个对象只需要使用唯一的一次,就可以用匿名对象。

Random类

此类的实例用于生成伪随机数。例如,以下代码使用户能够得到一个随机数:
Random r = new Random();
 int i = r.nextInt();

Random使用步骤

查看类
  • java.util.Random :该类需要 import导入使后使用。
查看构造方法
  • public Random() :创建一个新的随机数生成器。
查看成员方法
  • public int nextInt(int n) :返回一个伪随机数,范围在 0 (包括)和 指定值 n (不包括)之间的int 值。
  • public int nextInt( )  :返回一个伪随机数,范围是int所有范围,有正负两种。
举例

获取1-n之间的随机数,包含n,代码如下:

package demo03;


import java.util.Random;

/*

思路:
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);
        }
    }

}

题目:

用代码模拟猜数字的小游戏。

package demo03;


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类

到目前为止,我们想存储对象数据,选择的容器,只有对象数组。而数组的长度是固定的,无法适应数据变化的需求。为了解决这个问题,Java提供了另一个容器 java.util.ArrayList 集合类,让我们可以更便捷的存储和操作对象数据

什么是ArrayList类

java.util.ArrayList 是大小可变的数组的实现,存储在内的数据称为元素。此类提供一些方法来操作内部存储的元素。 ArrayList 中可不断添加元素,其大小也自动增长

ArrayList使用步骤

查看类
  • java.util.ArrayList <E> :该类需要 import导入使后使用。<E> ,表示一种指定的数据类型,叫做泛型。 E ,取自Element(元素)的首字母。在出现 E 的地方,我们使用一种引用数据类型将其替换即可,表示我们将存储哪种引用类型的元素。代码如下:
//泛型为String
ArrayList<String>
//泛型为Student
ArrayList<Student>
查看构造方法
  • public ArrayList() :构造一个内容为空的集合。
基本格式:

常用方法和遍历

对于元素的操作,基本体现在——增、删、查。常用的方法有:
  • public boolean add(E e) :将指定的元素添加到此集合的尾部。
  • public E remove(int index) :移除此集合中指定位置上的元素。返回被删除的元素。
  • public E get(int index) :返回此集合中指定位置上的元素。返回获取的元素。
  • public int size() :返回此集合中的元素数。遍历集合时,可以控制索引范围,防止越界。

举例:

package demo04;


import java.util.ArrayList;

/*
数组的长度不可以发生改变。
但是ArrayList集合的长度是可以随意变化的。

对于ArrayList来说,有一个尖括号<E>代表泛型。
泛型:也就是装在集合当中的所有元素,全都是统一的什么类型。
注意:泛型只能是引用类型,不能是基本类型。
 */
public class Demo03ArrayListMethod {

    public static void main(String[] args) {
        //创建arrayList集合,泛型为String
        ArrayList<String> list = new ArrayList<>();

        //对于ArrayList集合来说,直接打印得到的不是地址值,而是内容。如果内容是空,得到的是空的中括号:[]
        System.out.println(list); // []

        /*
        public boolean add(E e):向集合当中添加元素,参数的类型和泛型一致。返回值代表添加是否成功。
        备注:对于ArrayList集合来说,add添加动作一定是成功的,所以返回值可用可不用。
        但是对于其他集合(今后学习)来说,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); // [柳岩, 高圆圆, 赵又廷, 李小璐, 贾乃亮]

        //E get(int index):从集合当中获取元素,参数是索引编号,返回值就是对应位置的元素。
        String name = list.get(2);
        System.out.println("第2号索引位置:" + name); // 第2号索引位置:赵又廷

        // E remove(int index):从集合当中删除元素,参数是索引编号,返回值就是被删除掉的元素。
        String whoRemoved = list.remove(3);
        System.out.println("被删除的人是:" + whoRemoved); // 被删除的人是:李小璐
        System.out.println(list); // [柳岩, 高圆圆, 赵又廷, 贾乃亮]

        // int size():获取集合的尺寸长度,返回值是集合中包含的元素个数。
        int size = list.size();
        System.out.println("集合的长度是:" + size);//集合的长度是:4
    }

}

遍历集合

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对象不能存储基本类型,只能存储引用类型的数据。类似 <int> 不能写,但是存储基本数据类型对应的包装类型是可以的。所以,想要存储基本类型数据, <> 中的数据类型,必须转换后才能编写,转换写法如下: 

从JDK 1.5+开始,支持自动装箱、自动拆箱。

  • 自动装箱:基本类型 --> 包装类型
  • 自动拆箱:包装类型 --> 基本类型
我们发现,只有 Integer 和 Character 需要特殊记忆,其他基本类型只是首字母大写即可。那么存储基本类型数据,代码如下
package demo04;


import java.util.ArrayList;

/*
如果希望向集合ArrayList当中存储基本类型数据,必须使用基本类型对应的“包装类”。

基本类型    包装类(引用类型,包装类都位于java.lang包下)
byte        Byte
short       Short
int         Integer     【特殊】
long        Long
float       Float
double      Double
char        Character   【特殊】
boolean     Boolean

 */
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);//第1号元素是:200
    }

}

需求

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

代码实现

package cn.itcast.day07.demo05;

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

/*
思路:
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));
        }
    }

}

需求

自定义4个学生对象,添加到集合,并遍历。

定义student类

package demo04;



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

添加到集合中

package demo04;


import java.util.ArrayList;

/*

思路:
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());
        }
    }

}

需求

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

代码实现

package demo04;


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

/*

分析:
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 对象
        ArrayList<Integer> bigList = new ArrayList<>();
        // 创建Random 对象
        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);

    }

    // 这个方法,接收大集合参数,返回小集合结果
    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;
    }

}

 

猜你喜欢

转载自www.cnblogs.com/wurengen/p/12230174.html
今日推荐