Java基础(12)Scanner类、String类

1.Scanner类

1. Scanner类概述:一个可以使用正则表达式来解析基本类型和字符串的简单文本扫描器
2. Scanner的构造方法:Scanner(InputStream source)
3. Scanner类下有一个静态的字段:public static final InputStream in;(标准输入流)
4. 常用方法
(1)hasNextXxx():判断下一个是否是某种类型的元素
(2)nextXxx():获取下一个输入项

public class ScannerDemo01 {
    public static void main(String[] args) {
        InputStream is = System.in;
        Scanner sc = new Scanner(is);  //等同于:Scanner sc = new Scanner(System.in);

        //录入数字
        int i = sc.nextInt();
        double d = sc.nextDouble();
        long l = sc.nextLong();

        //录入布尔类型
        boolean b = sc.nextBoolean();

        //录入字符串
        String s = sc.nextLine();
    }
}

5. 有一个小bug需要注意一下

public class ScannerDemo02 {
    public static void main(String[] args) {
        //当我们录入完一个整数的时候,接着录入字符串,发现字符串并没有录入进去
        //因为当我们录入完整数后,敲击回车键,IDEA会把“回车键”当做字符串进行录入
       /*
        Scanner sc = new Scanner(System.in);

        System.out.println("请输入一个数字");
        int i = sc.nextInt();
        System.out.println(i);

        System.out.println("请输入一个字符串");
        String s = sc.nextLine();
        System.out.println(s);
        */

        //解决办法:在录入完整数后,重新创建一个Scanner对象
        Scanner sc = new Scanner(System.in);

        System.out.println("请输入一个数字");
        int i = sc.nextInt();
        System.out.println(i);

        //重新创建Scanner对象
        sc = new Scanner(System.in);
        System.out.println("请输入一个字符串");
        String s = sc.nextLine();
        System.out.println(s);
    }
}

6. 让用户输入整数并打印的小案例

public class ScannerDemo03 {
    public static void main(String[] args) {
        while(true){
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入一个整数");
            if(sc.hasNextInt()){
                int i = sc.nextInt();
                System.out.println(i);
                break;
            }else {
                System.out.println("输入的数据不对,请重新输入");
            }
        }
    }
}

2.String类

1. 字符串的概述:字符串是由多个字符组成的一串数据(字符序列)
2. 字符串可以看成是字符数组,字符串的每个字符,从左往右编有索引,从0开始
3. 构造方法
(1)public String():空参构造
(2)public String(String original):把字符串常量值转成字符串

public class TestDemo01 {
    public static void main(String[] args) {
        //空字符序列
        String s = new String();
        System.out.println(s);  //
        //String类重新了toString方法,直接打印字面值
        System.out.println(s.toString());   //

        String s2 = new String("abc");
        System.out.println(s2);  //abc
        System.out.println(s2.toString());  //abc

    }
}

(3)public String(byte[] bytes):把字节数组转成字符串
(4)public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串(index:表示的是从第几个索引开始, length表示的是长度)

public class TestDemo02 {
    public static void main(String[] args) {
        //定义一个字节数组
        byte[] bytes = {97,98,99,100};

        String s1 = new String(bytes);
        System.out.println(s1);  //abcd

        String s2 = new String(bytes,0,2);
        System.out.println(s2);  //ab
        
    }
}

(5)public String(char[] value):把字符数组转成字符串
(6)public String(char[] value,int index,int count):把字符数组的一部分转成字符串

public class TestDemo03 {
    public static void main(String[] args) {
        char[] chars = {'a','b','c','英','雄','联','盟'};

        String s1 = new String(chars);
        System.out.println(s1);  //abc英雄联盟

        String s2 = new String(chars,3,4);
        System.out.println(s2);   //英雄联盟
    }
}

4. 获取字符串长度:public int length()

public class TestDemo01 {
    public static void main(String[] args) {
        String s1 = new String("abcde");
        int i1 = s1.length();
        System.out.println(i1);  //5

        //字符串字面值"cdef"也可以看成是一个字符串对象。
        int i2 = "cdef".length();
        System.out.println(i2);  //4
    }
}

5. 字符串的特点:字符串常量一旦被创建,就不能被改变。因为字符串的值是在堆内存的字符串常量池中划分的,分配地址值的
(1)案例演示①

public class TestDemo02 {
    public static void main(String[] args) {
        String s = "LOL";
        s = "hello " + "world";
        System.out.println(s);  //hello world
    }
}

在这里插入图片描述

(2)案例演示②:String s1 = new String(“hello”) 和 String s2 = "hello"的区别

public class TestDemo03 {
    public static void main(String[] args) {
       
        String s1  = new String("hello");
        
        String s2 = "hello";
    }
}

在这里插入图片描述
在这里插入图片描述
(3)案例演示③

public class TestDemo04 {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        System.out.println(s1 == s2);           //false
        System.out.println(s1.equals(s2));      //true

        String s3 = new String("hello");
        String s4 = "hello";
        System.out.println(s3 == s4);           //false
        System.out.println(s3.equals(s4));      //true

        String s5 = "hello";
        String s6 = "hello";
        System.out.println(s5 == s6);          //true
        System.out.println(s5.equals(s6));     //true
    }
}

(4)案例演示④

public class MyTest4 {
    public static void main(String[] args) {
        //当我们采用 字符串字面值 这种方式来定义一个字符串的时候,
        // 他会先去字符串常量池去查找有没有有该字符串,如果没有,就构建这个字符串。
        //如果有,就把字符串常量池中这个字符串的地址值,赋值给这个新的引用
        String s1 = "hello";
        String s2 = "hello";
        String s3 = "abc";
        String s4 = new String("world");
        System.out.println(s1 == s2); //true
        System.out.println(s2 == s3); //false
        System.out.println(s4 == s3);//false
    }
}

在这里插入图片描述
6. String类的常用方法

(1)判断功能

  • public boolean equals(Object obj):比较两个字符串的内容是否相同(区分大小写)
  • public boolean equalsIgnoreCase(Object obj) :比较两个字符串的内容是否相同(不区分大小写)
public class TestDemo01 {
    public static void main(String[] args) {
        //public boolean equals(Object obj):比较两个字符串的内容是否相同(区分大小写)
        boolean b1 = "abc".equals("ABC");
        System.out.println(b1);  //false

		//public boolean equalsIgnoreCase(Object obj) :比较两个字符串的内容是否相同(不区分大小写)
        boolean b2 = "abc".equalsIgnoreCase("ABC");
        System.out.println(b2);  //true
    }
}
  • public boolean contains(String str):字符串中是否包含传递进来的字符串
  • public boolean startsWith(String str):判断字符串是否以传进来的字符串开头
  • public boolean endWith(String str):判断字符串是否以传进来的字符串结尾
  • public boolean isEmpty():判断字符串是否是空字符串
public class TestDemo02 {
    public static void main(String[] args) {
        String str1 = "啦啦啦德玛西亚";

        //public boolean contains(String str):字符串中是否包含传递进来的字符串
        boolean b1 = str1.contains("德玛");
        System.out.println(b1);  //true

        // public boolean startsWith(String str):判断字符串是否以传进来的字符串开头
        boolean b2 = str1.startsWith("啦啦啦");
        System.out.println(b2);  //true

        //public boolean endWith(String str):判断字符串是否以传进来的字符串结尾
        boolean b3 = str1.endsWith("哈哈");
        System.out.println(b3);  //false

        //public boolean isEmpty():判断字符串是否是空字符串
        boolean b4 = str1.isEmpty();
        System.out.println(b4);   //false

        String str2 = "";
        System.out.println(str2.isEmpty());  //false
    }
}
  • 案例演示:模拟登陆,给三次机会,并提示还有几次
import java.util.Scanner;

public class TestDemo03 {
    public static void main(String[] args) {
        String userName = "vn";
        String passWord = "123456";
        Scanner sc = new Scanner(System.in);

        for (int i = 1; i <= 3; i++) {
            System.out.println("请输入用户名");
            String uName = sc.nextLine();
            System.out.println("请输入密码");
            String psw = sc.nextLine();
            if(uName.equals(userName) && psw.equals(passWord)){
                System.out.println("登陆成功");
                break;
            }else {
                if((3-i) != 0){
                    System.out.println("登陆失败,你还有" + (3 - i) + "次机会" );
                }else {
                    System.out.println("账号已被冻结");
                }
            }
        }
    }
}

(2)获取功能

  • public int length():获取字符串的长度
  • public char charAt(int index):获取指定索引位置的字符
  • public int indexOf(char ch):返回指定字符在此字符串中第一次出现处的索引
  • public int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引
  • public int indexOf(char ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引
  • public int indexOf(String str,int fromIndex) :返回指定字符串在此字符串中从指定位置后第一次出现处的索引
  • public String substring(int start):从指定位置开始截取字符串,默认到末尾
  • public String substring(int start,int end): 从指定位置开始到指定位置结束截取字符串(包括前面,不包括后面)
public class TestDemo01 {
    public static void main(String[] args) {
        String str1 = "啦啦啦德玛西亚";

        //public int length():获取字符串的长度
        int length = str1.length();
        System.out.println(length);  //7

        //public char charAt(int index):获取指定索引位置的字符
        char c = str1.charAt(5);
        System.out.println(c);   //西

        //public int indexOf(char ch):返回指定字符在此字符串中第一次出现处的索引
        int i1 = str1.indexOf('德');
        System.out.println(i1);   //3

        //public int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引
        int i2 = str1.indexOf("啦德玛");
        System.out.println(i2);  //2

        //public int indexOf(char ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引
        int i3 = str1.indexOf('啦', 1);
        System.out.println(i3);  //1

        //public int indexOf(String str,int fromIndex) :返回指定字符串在此字符串中从指定位置后第一次出现处的索引
        int i4 = str1.indexOf("德玛", 2);
        System.out.println(i4);  //3

        // String substring(int start):从指定位置开始截取字符串,默认到末尾
        String substring1 = str1.substring(2);
        System.out.println(substring1);   //啦德玛西亚

        //public String substring(int start,int end):	从指定位置开始到指定位置结束截取字符串(包括前面,不包括后面)
        String substring2 = str1.substring(1, 4);
        System.out.println(substring2);   //啦啦德
    }
}
  • 案例演示:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)
public class TestDemo02 {
    public static void main(String[] args) {
        String str = "asdfASDJ18E9czc12";
        int numDa = 0;
        int numXiao = 0;
        int numShu = 0;

        for (int i = 0; i < str.length(); i++) {
            if(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){
                numDa++;
            }else if(str.charAt(i) >= 'a' && str.charAt(i) <= 'z'){
                numXiao++;
            }else if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){
                numShu++;
            }
        }

        System.out.println("大写字符有:" + numDa + "个");  //大写字符有:5个
        System.out.println("小写字符有:" + numXiao + "个");  //小写字符有:7个
        System.out.println("数字有:" + numShu + "个");   //数字有:5个
    }
}

(3)转换功能

  • public byte[] getBytes():把字符串转换为字节数组
  • public char[] toCharArray():把字符串转换为字符数组
  • public static String valueOf(char[] chs):把字符数组转成字符串
  • public static String valueOf(int i):把int类型的数据转成字符串
  • 注意:String类的valueOf方法可以把任意类型的数据转成字符串
  • public String toLowerCase():把字符串转成小写
  • public String toUpperCase():把字符串转成大写
  • public String concat(String str):拼接字符串
public class TestDemo01 {
    public static void main(String[] args) {

        //public byte[] getBytes():把字符串转换为字节数组
        String str1 = "abcd";
        byte[] bytes = str1.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);   //97 98 99 100
        }
        //把字节数组转化成字符串
        String s = new String(bytes);
        System.out.println(s);   //abcd

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

        //public char[] toCharArray():把字符串转换为字符数组
        String str2 = "德玛西亚";
        char[] chars = str2.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            System.out.println(chars[i]);    //德 玛 西 亚
        }
        //把字符数组转换成字符串
        String s1 = new String(chars);
        System.out.println(s1);   //德玛西亚

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

        //public static String valueOf(char[] chs):把字符数组转成字符串
        char[] chs = {'伊','泽','瑞','尔'};
        String str3 = String.valueOf(chs);
        System.out.println(str3);   //伊泽瑞尔

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

        //public static String valueOf(int i):把int类型的数据转成字符串
        String str4 = String.valueOf(100);
        System.out.println(str4);   //100

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

        //public String toLowerCase():把字符串转成小写
        //public String toUpperCase():把字符串转成大写
        String str5 = "ADfkjASC";
        String s2 = str5.toLowerCase();
        System.out.println(s2);           //adfkjasc
        String s3 = str5.toUpperCase();
        System.out.println(s3);           //ADFKJASC

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

        //public String concat(String str):拼接字符串
        String str = "金克斯".concat("没有胸哈哈哈");
        System.out.println(str);   //金克斯没有胸哈哈哈

    }
}
  • 案例演示:给定一个字符串,除了首字母大写外,其余全是小写
public class TestDemo02 {
    public static void main(String[] args) {
        String str = "ASKLJjklcaSA";

        //链式编程
        String s = str.substring(0, 1).toUpperCase().concat(str.substring(1).toLowerCase());
        System.out.println(s);   //Askljjklcasa
    }
}

(4)其他功能

  • public String replace(char old,char new):将指定字符进行互换
  • public String replace(String old,String new):将指定字符串进行互换
  • public String trim() :去除两端空格
  • public int compareTo(String str):会对照ASCII 码表 从第一个字母进行减法运算,返回的就是这个减法的结果。如果前面几个字母一样会根据两个字符串的长度进行减法运算返回的就是这个减法的结果。如果连个字符串一摸一样,返回的就是0
public class TestDemo01 {
    public static void main(String[] args) {
        //public String replace(char old,char new):将指定字符进行互换
        String str1 = "周淑怡没有胸";
        String s1 = str1.replace('胸', '*');
        System.out.println(s1);   //周淑怡没有*

        //public String replace(String old,String new):将指定字符串进行互换
        String str2 = "特朗普是傻逼";
        String s2 = str2.replace("傻逼", "**");
        System.out.println(s2);   //特朗普是**

        //public String trim():去除两端空格
        String str3 = "  略略略   ";
        System.out.println(str3);   //  略略略
        String s3 = str3.trim();
        System.out.println(s3);   //略略略


        //public int compareTo(String str):会对照ASCII 码表 从第一个字母进行减法运算 返回的就是这个减法的结果
        int i1 = "abc".compareTo("Abc");
        System.out.println(i1);   //32  a->97  A->65

        int i2 = "abc".compareTo("abc");
        System.out.println(i2);   //0

        int i3 = "abc".compareTo("abcd");
        System.out.println(i3);   //-1   abc->3位数   abcd->4位数
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值