Java中的常用类(Scanner类、Random类、ArrayList类、 Strings类、Array类、Math类)的说明及基本使用方法

常用类

API(Application Programming Interface)概述

API(Application Programming Interface),应用程序编程接口(文档说明书)。Java API是一本程序员的 字典 ,是JDK中提供给我们使用的类的说明文档。

API使用步骤

  1. 打开说明文档。
  2. 打开索引,搜索查询的类名。
  3. 查看该类所属的包,java.lang下的类不需要导包,其他需要(idea自动导包)。
  4. 查看该类的构造器,明白如何使用该类创建对象。
  5. 查看该类的成员方法,明白该类的使用。

Scanner类

Scanner使用步骤

  • 查看类
    • java.util.Scanner :该类需要import导入后使用。
  • 查看构造方法
    • public Scanner(InputStream source) : 构造一个新的 Scanner ,它生成的值是从指定的输入流扫描的。
  • 查看成员方法
    • public int nextInt() :将输入信息的下一个标记扫描为一个 int 值。
导包
import 包名.类名;
创建对象
数据类型 变量名 = new 数据类型(参数列表);
调用方法
变量名.方法名();
举例
import java.util.Scanner;//导包,java.lang包下的所有类无需导入
Scanner sc = new Scanner(System.in);//创建对象
int i = sc.nextInt();//调用方法
String str = sc.nextLine();
double dou = sc.nextDouble();

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

输入三个数求最大值
import java.util.Scanner;
public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入第一个数");
        int a = scanner.nextInt();
        System.out.println("请输入第二个数");
        int b = scanner.nextInt();
        System.out.println("请输入第三个数");
        int c = scanner.nextInt();

        int max = (a>b?a:b)>c?(a>b?a:b):c;
        System.out.println("最大值为:"+max);

    }

匿名对象

创建对象时,只有创建对象的语句,却没有把对象地址值赋值给某个变量。虽然是创建对象的简化写法,但是应用场景非常有限。

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

new 类名(参数列表);
new Scanner(System.in);

应用场景

  1. 创建匿名对象直接调用方法,没有变量名。
  2. 一旦调用两次方法,就是创建了两个对象,造成浪费
  3. 匿名对象可以作为方法的参数和返回值

一个匿名对象,只能使用一次。

Random类

Random使用步骤

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

举例

Random r = new Random();
int i = r.nextInt();
int j = r.nextInt(100);//0<=j<100

备注:创建一个 Random 对象,每次调用 nextInt() 方法,都会生成一个随机数。

猜数字游戏
import java.util.Random;
import java.util.Scanner;

public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        Random r = new Random();
        int num = r.nextInt(100)+1;
        while(true){
            System.out.println("请输入一个数:");
            int getnum = s.nextInt();
            if(num == getnum){
                System.out.println("您猜对了,游戏结束");
                break;
            }else if(num > getnum){
                System.out.println("您输入的数过小,请重新输入");
            }else{
                System.out.println("您输入的数过大,请重新输入");
            }
        }
    }

ArrayList类

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

ArrayList使用步骤

  • 查看类
    • java.util.ArrayList :该类需要 import导入使后使用。
    • ,表示一种指定的数据类型,叫做泛型。 E ,取自Element(元素)的首字母。在出现 E 的地方,我们使用一种引用数据类型将其替换即可,表示我们将存储哪种引用类型的元素。
ArrayList<String>,ArrayList<Student>
  • 查看构造方法
    • public ArrayList() :构造一个内容为空的集合。
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list = new ArrayList<>();
  • 查看成员方法
    • public boolean add(E e) : 将指定的元素添加到此集合的尾部。
    • 参数 E e ,在构造ArrayList对象时, 指定了什么数据类型,那么 add(E e) 方法中,只能添加什么数据类型的对象。

常用方法和遍历

对于元素的操作,基本体现在——增、删、查。常用的方法有:

public boolean add(E e) :将指定的元素添加到此集合的尾部。

public E remove(int index) :移除此集合中指定位置上的元素。返回被删除的元素。

public E get(int index) :返回此集合中指定位置上的元素。返回获取的元素。

public int size() :返回此集合中的元素数。遍历集合时,可以控制索引范围,防止越界。

		ArrayList<String> list = new ArrayList<>();//构造一个初始容量为十的空列表。
        ArrayList<String> list1 = new ArrayList<String>(100);//构造具有指定初始容量的空列表。
        ArrayList<String> list2 = new ArrayList<>(list);//ArrayList​(Collection<? extends E> c)构造一个包含指定集合的元素的列表,按照它们由集合的迭代器返回的顺序。

        String s1 = "张大";
        String s2 = "张二";
        String s3 = "张三";

        System.out.println(list);

        list.add(s1);
        list.add(s2);
        list.add(s3);//将指定的元素追加到此列表的末尾。
        System.out.println(list);

        String s4 = "张四";
        list.add(1,s4);//在此列表中的指定位置插入指定的元素。
        System.out.println(list);

        System.out.println(list.remove(0));//移除此集合中指定位置上的元素。返回被删除的元素。
        System.out.println(list);

        System.out.println(list.get(0));//返回此集合中指定位置上的元素。返回获取的元素。
        System.out.println(list);

        System.out.println(list.size());//返回此集合中的元素数。遍历集合时,可以控制索引范围,防止越界。

        list1.addAll(list);//按指定集合的Iterator返回的顺序将指定集合中的所有元素追加到此列表的末尾。
        list2.addAll(list);
        System.out.println(list1);

        list1.addAll(1,list);//将指定集合中的所有元素插入到此列表中,从指定的位置开始。
        System.out.println(list1);

        list.clear();//从列表中删除所有元素。
        System.out.println(list);

        System.out.println(list1.contains("张四"));//如果此列表包含指定的元素,则返回 true 。

        System.out.println(list1.indexOf("张四"));//返回此列表中指定元素的第一次出现的索引,如果此列表不包含元素,则返回-1。
        System.out.println(list1.lastIndexOf("张四"));//返回此列表中指定元素的最后一次出现的索引,如果此列表不包含元素,则返回-1。
        System.out.println(list1.indexOf("赵一"));//返回此列表中指定元素的第一次出现的索引,如果此列表不包含元素,则返回-1。

        System.out.println(list.isEmpty());//如果此列表不包含元素,则返回 true 。
        System.out.println(list1.isEmpty());

        System.out.println(list1.remove(0));//删除该列表中指定位置的元素。
        System.out.println(list1);

        System.out.println(list1.remove("张三"));//从列表中删除指定元素的第一个出现(如果存在)。
        System.out.println(list1);

        System.out.println(list1.removeAll(list2));//从此列表中删除指定集合中包含的所有元素。
        System.out.println(list1);

ArrayList存储基本数据类型

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

基本类型基本类型包装类
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean
public class Demo02ArrayListMethod {
public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<Integer>();
    ArrayList<Character> list1 = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(4);
    list1.add('a');
    list1.add('1');
    System.out.println(list);
    System.out.println(list1);
} 
}
数值添加到集合
public static void add_num(){
    Random random = new Random();
    ArrayList<Integer> list = new ArrayList<>();
    for (int i = 0; i < 6; i++) {
        int r = random.nextInt(33)+1;
        list.add(r);
    }
    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i));
    }
}

Strings类

java.lang.String 类代表字符串。

特点
  1. 字符串不变:字符串的值在创建后不能被更改。
  2. 因为String对象是不可变的,所以它们可以被共享。
  3. “abc” 等效于 char[] data={ ‘a’ , ‘b’ , ‘c’ } 。
String s1 = "abc";
s1 += "d";
System.out.println(s1); // "abcd"
// 内存中有"abc","abcd"两个对象,s1从指向"abc",改变指向,指向了"abcd"。

String s1 = "abc";
String s2 = "abc";
// 内存中只有一个"abc"对象被创建,同时被s1和s2共享。

//例如:
String str = "abc";
//相当于:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
// String底层是靠字符数组实现的。
使用步骤
  • 查看类
    • java.lang.String :此类不需要导入。
  • 查看构造方法
    • public String() :初始化新创建的 String对象,以使其表示空字符序列。
    • public String(char[] value) :通过当前参数中的字符数组来构造新的String。
    • public String(byte[] bytes) :通过使用平台的默认字符集解码当前参数中的字节数组来构造新的String。
// 无参构造
        String str = new String();
        System.out.println(str);
        // 通过字符数组构造
        char chars[] = {'a', 'b', 'c'};
        String str2 = new String(chars);
        System.out.println(str2);
        // 通过字节数组构造
        byte bytes[] = { 97, 98, 99 };//a:97,b:87,c:99
        String str3 = new String(bytes);
        System.out.println(str3);

常用方法

  • 判断功能的方法
    • public boolean equals (Object anObject) :将此字符串与指定对象进行比较。Object 是” 对象”的意思,也是一种引用类型。作为参数类型,表示任意对象都可以传递到方法中。
    • public boolean equalsIgnoreCase (String anotherString) :将此字符串与指定对象进行比较,忽略大小写。
  • 获取功能的方法
    • public int length () :返回此字符串的长度。
    • public String concat (String str) :将指定的字符串连接到该字符串的末尾。
    • public char charAt (int index) :返回指定索引处的 char值。
    • public int indexOf (String str) :返回指定子字符串第一次出现在该字符串内的索引。
    • public String substring (int beginIndex) :返回一个子字符串,从beginIndex开始截取字符串到字符串结尾。
    • public String substring (int beginIndex, int endIndex) :返回一个子字符串,从beginIndex到endIndex截取字符串。含beginIndex,不含endIndex。
  • 转换功能的方法
    • public char[] toCharArray () :将此字符串转换为新的字符数组。
    • public byte[] getBytes () :使用平台的默认字符集将该 String编码转换为新的字节数组。
    • public String replace (CharSequence target, CharSequence replacement) :将与target匹配的字符串使用replacement字符串替换。CharSequence 是一个接口,也是一种引用类型。作为参数类型,可以把String对象传递到方法中。
  • 分割功能的方法
    • public String[] split(String regex) :将此字符串按照给定的regex(规则)拆分为字符串数组。
 public static void main(String[] args) {
        String s = "abc";//java.lang.String不需要导入
        s += "1";
        System.out.println(s);

        // 无参构造
        String str = new String();
        System.out.println(str);
        // 通过字符数组构造
        char chars[] = {'a', 'b', 'c'};
        String str2 = new String(chars);
        System.out.println(str2);
        // 通过字节数组构造
        byte bytes[] = { 97, 98, 99 };//a:97,b:87,c:99
        String str3 = new String(bytes);
        System.out.println(str3);
     
        //判断功能的方法
        System.out.println(str2 == str3);
        System.out.println(str2.equals(str3));//将此字符串与指定对象进行比较。
        System.out.println("‐‐‐‐‐‐‐‐‐‐‐");

        String str4 = "ABC";
        System.out.println(str2.equals(str4));
        System.out.println(str2.equalsIgnoreCase(str4));//将此字符串与指定对象进行比较,忽略大小写。
        System.out.println("‐‐‐‐‐‐‐‐‐‐‐");

        //获取功能的方法
        System.out.println(str2.length());//返回此字符串的长度。
        System.out.println(
                str2.concat(str4)//str2本身未发生改变
        );//将指定的字符串连接到该字符串的末尾。
        System.out.println(str2);

        System.out.println(str2.charAt(2));//返回指定索引处的 char值。
        System.out.println(str4.indexOf("A"));//返回指定子字符串第一次出现在该字符串内的索引。

        System.out.println(str2.substring(1));//返回一个子字符串,从beginIndex开始截取字符串到字符串结尾。

        System.out.println(str2.substring(0,2));//返回一个子字符串,从beginIndex到endIndex截取字符串。含beginIndex,不含endIndex。
        System.out.println("‐‐‐‐‐‐‐‐‐‐‐");

        //转换功能的方法
        char[] c = str4.toCharArray();//将此字符串转换为新的字符数组。
        System.out.println(c);

        char[] chs = s.toCharArray();
        System.out.println(chs);
        for(int x = 0; x < chs.length; x++) {
            System.out.print(chs[x]);
        }
        System.out.println();


        byte[] b = str4.getBytes();//使用平台的默认字符集将该 String编码转换为新的字节数组。
//        System.out.println(b);
        for (int i = 0; i < b.length; i++) {
            System.out.print(b[i]);
        }
        System.out.println();

        String replace = str2.replace("a","B");//将与target匹配的字符串使用replacement字符串替换。
        System.out.println(replace);
        System.out.println("‐‐‐‐‐‐‐‐‐‐‐");


        //分割功能的方法
        String s1 = "aa/bb/cc";//|不能分割
        String[] strArray = s1.split("/"); // ["aa","bb","cc"]
        for(int x = 0; x < strArray.length; x++) {
            System.out.println(strArray[x]); // aa bb cc
        }

    }

string类及常量池

String类的练习

拼接字符串
public static void main(String[] args) {
        int[] arr = {1,2,3};
        String s = arrayToString(arr);
        System.out.println(s);

    }

    public static String arrayToString(int[] arr){
        String s = "[";
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length-1){
                s = s.concat(arr[i] + "]");
            }else{
                s = s.concat(arr[i] + "#");
            }
        }
        return s;

    }
统计字符个数
public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个字符串数据:");
        String s = scanner.nextLine();

        int bigCount = 0;
        int smallCount = 0;
        int numberCount = 0;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(c >= 'A' && c <= 'Z'){
                bigCount++;
            }else if(c >= 'a' && c <= 'z'){
                smallCount++;
            }else if(c >= '0'&& c <= '9'){
                numberCount++;
            }else {
                System.out.println("该字符" + c + "非法");
            }
        }

        System.out.println("大写字符"+bigCount+"个");
        System.out.println("小写字符"+smallCount+"个");
        System.out.println("数字字符"+numberCount+"个");
    }

Array类

java.util.Arrays 此类包含用来操作数组的各种方法

操作数组的方法
  • public static String toString(int[] a) :返回指定数组内容的字符串表示形式。
  • public static void sort(int[] a) :对指定的 int 型数组按数字升序进行排序。
public static void main(String[] args) {
        int[] arr = {2,15,49,85,64,28,15,1,0};
        System.out.println(arr);//输出地址值
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+"\t");
        }
        System.out.println();

        //返回指定数组内容的字符串表示形式。
        String s = Arrays.toString(arr);
        System.out.println(s);

        //对指定的 int 型数组按数字升序进行排序。
        System.out.println("排序前:"+Arrays.toString(arr));

        // 升序排序
        Arrays.sort(arr);
        System.out.println("排序后:"+Arrays.toString(arr));

        show();
    }

    public static void show(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入随机字符");
        String str = scanner.nextLine();
        char[] chars = str.toCharArray();

        Arrays.sort(chars);
        for (int i = chars.length-1; i >= 0; i--) {
            System.out.print(chars[i]+" ");
        }

    }

Math类

java.lang.Math 类包含用于执行基本数学运算的方法

基本运算的方法
  • public static double abs(double a) :返回 double 值的绝对值。
  • public static double ceil(double a) :返回大于等于参数的最小的整数。
  • public static double floor(double a) :返回小于等于参数最大的整数
  • public static long round(double a) :返回最接近参数的 long。(相当于四舍五入方法)
public static void main(String[] args) {
        //返回 double 值的绝对值。
        double d1 = Math.abs(-5);
        double d2 = Math.abs(5);
        System.out.println(d1);//5.0
        System.out.println(d2);//5.0

        //返回大于等于参数的最小的整数。
        double d3 = Math.ceil(3.3);
        double d4 = Math.ceil(-3.3);
        double d5 = Math.ceil(5.1);
        System.out.println(d3);//4.0
        System.out.println(d4);//-3.0
        System.out.println(d5);//6.0

        //返回小于等于参数最大的整数
        double d6 = Math.floor(3.3);
        double d7 = Math.floor(-3.3);
        double d8 = Math.floor(5.1);
        System.out.println(d6);//3.0
        System.out.println(d7);//-4.0
        System.out.println(d8);//5.0

        //返回最接近参数的 long。(相当于四舍五入方法)
    	long d9 = Math.round(5.5); //d1的值为6
		long d10 = Math.round(5.4); //d2的值为5
    	System.out.println(d9);
        System.out.println(d10);
    
        double min = -10.8;
        double max = 5.9;
        int count = 0;
        for (double i = Math.ceil(min); i < max; i++) {
            if(Math.abs(i)>6||Math.abs(i)<2.1){
                count++;
            }
        }
        System.out.println("个数为:"+count+"个");//9

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值