Java复习之路-day12-常见对象(Scanner类、String类)

常见对象(Scanner类、String类)

  1. 常见对象(Scanner的概述和方法介绍)
  • A:Scanner的概述
  • B:Scanner的构造方法原理:
    • Scanner(InputStream source)
    • System类下有一个静态字段:
      • public static final InputStream in;标准的输入流,对应着键盘录入。
  • C:一般方法
    • hasNextXxx():判断是否还有下一个输入项,其中Xxx可以是Int、Double等。如果需要判断是否包含下一个字符串,则可以省略Xxx
    • nextXxx():获取下一个输入项。Xxx的含义和上个方法中的Xxx相同。默认情况下,Scanner使用空格,回车等作为分隔符。
import java.util.Scanner;

public class Demo1_Scanner {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); // 键盘录入
        //int i = sc.nextInt(); // 键盘录入整数存储在i中
        //System.out.println(i);

        if (sc.hasNextInt()) {
            int i = sc.nextInt();
            System.out.println(i);
        } else {
            System.out.println("输入类型错误");
        }
    }
}
  1. 常见对象(Scanner获取数据出现的小问题及解决方案)
  • A:两个常用的方法:
    • public int nextInt();获取一个int类型的值
    • public String nextLine();获取一个String类型的值
  • B:案例演示
    • a:先演示获取多个int值,多个String值的情况
    • b:在演示先获取int值,然后获取String值出现的问题
    • c:问题解决方案:
      • 第一种:先获取一个数值后,在创建一个新的键盘录入对象获取字符串。
      • 第二种:把所有的数据都先按照字符串获取,然后要什么,你就对象的转换为什么。
public class Demo2_Scanner {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        /*System.out.println("请输入第一个整数:");
        int i = sc.nextInt();
        System.out.println("请输入第二个整数:");
        int j = sc.nextInt();
        System.out.println("i = " + i + ", j = " + j);*/

       /*System.out.println("请输入第一个字符串:");
        String line1 = sc.nextLine();
        System.out.println("请输入第二个字符串:");
        String line2 = sc.nextLine();
        System.out.println("line1 =" + line1 + ", line2 = " + line2);*/

        /*
         *下面代码有问题,运行结果为:
         *  请输入第一个整数:
            12
            请输入第二个字符串:
            i =12, line2 =
         *
         * 原因:
         * nextInt()是键盘录入整数的方法,当录入10的时候,其实就在键盘上录入的是
         * 10和\r\n,nextInt()方法只获取10就结束了,nextLine()是键盘录入字符串的方法
         * 可以接收任意类型,但是它获取一行也是有所根据的,即:遇到\r\n就证明一行结束。
         * 
         * 解决方法:
         * 1. 创建两次对象,不过浪费空间
         * 2. 键盘录入的都是字符串,都用nextLine方法,然后讲整数字符串转化为整数(方法后面讲到)
         */
        System.out.println("请输入第一个整数:");
        int i = sc.nextInt();
        System.out.println("请输入第二个字符串:");
        String line2 = sc.nextLine();
        System.out.println("i =" + i + ", line2 = " + line2);
    }
}
  1. 常见对象(String类的概述)
    *A: String类的概述:
    • 通过JDK提供的API,查看String类的说明
    • 可以看到这样的两句话
      • a:字符串字面值“abc"也可以看成是一个字符串对象。
      • b:字符串是常量,一旦被赋值,就不能被改变
public class Demo1_String {
    public static void main(String[] args) {
        String str = "abc"; //"abc"可以看成一个字符串对象
        System.out.println(str); // String类重写了toString(),返回该对象本身
        str = "Def"; // 当把"Def"赋值给str,原来的"acb"就变成了垃圾
        System.out.println(str);
    }
}
  1. 常见对象(String类的构造方法)
    *A:常见构造方法
    • public String():空构造
    • public String(byte[] bytes):把字节数组专成字符串
    • public String(byte[] bytes, int index, int length):把字节数组的一部分转成字符串
    • public String(char[] value):把字符数组专成字符串
    • public String(char[] value, int index, int count):把字符数组的一部分转成字符串。
    • public String(String original):把字符常量值转成字符串。
public class Demo2_StringCon {
    public static void main(String[] args) {
        String s1 = new String();
        System.out.println(s1);

        byte[] arr1 = {97, 98, 99};
        String s2 = new String(arr1); // 解码,将计算机读得懂的转换成我们读得懂的
        System.out.println(s2);

        byte[] arr2 = {97, 98, 99, 100, 101, 102};
        String s3 = new String(arr2, 2, 3); //将arr2字节数组从2索引开始转换3个
        System.out.println(s3);

        char[] arr3 = {'a', 'b', 'c', 'd', 'e'};
        String s4 = new String(arr3); //将字符数组转换成字符串
        System.out.println(s4);

        String s5 = new String(arr3, 1, 3); //将arr3字符数组,从1索引开始转换3个
        System.out.println(s5);

        String s6 = new String("heima");
        System.out.println(s6);
    }
}
  1. 常见对象(String类的常见面试题)
public class Demo3_String {
    public static void main(String[] args) {
        //demo1();
        //demo2();
        //demo3();
        //demo4();
        demo5();
    }

    private static void demo5() {
        String s1 = "ab";
        String s2 = "abc";
        String s3 = s1 + "c";
        System.out.println(s3 == s2); // flase。因为此行中,s1是变量,所以要入堆,经过StringBuffer和toString()方法转换成String
        System.out.println(s3.equals(s2)); // true
    }

    private static void demo4() {
        String s1 = "a" + "b" + "c";
        String s2 = "abc";
        System.out.println(s1 == s2); // true,Java中有常量优化机制,在编译时就变成了“abc"
        System.out.println(s1.equals(s2)); // true
    }

    private static void demo3() {
        String s1 = new String("abc"); //记录的是堆的
        String s2 = "abc"; // 记录的是常量池中的地址值
        System.out.println(s1 == s2); // false,
        System.out.println(s1.equals(s2)); // true
    }

    private static void demo2() {
        //创建几个对象? 答:创建2个,一个在常量池,一个在堆内存中
        String s1= new String("abc");
        System.out.println(s1);
    }

    private static void demo1() {
        String s1 = "abc";
        String s2 = "abc";
        System.out.println(s1 == s2); // true
        System.out.println(s1.equals(s2)); // true
    }
}

demo1()的内存图解析:e656b6170685da4796e91f17b6e702fc.png
demo2()的内存图解析:
0c4b4606ce6f3b7ca18054dd4d9cc45b.png
demo5()的内存图解析:
e685bace135fe4d1a593da0b639cf1ea.png
6. 常见对象(String类的判断功能):

  • boolean equals(Object obj):比较字符串的内容是否相同,区分大小写。
  • boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写。
  • boolean contains(String str):判断大字符串中是否包含小字符串
  • boolean endsWith(String str):判断字符串是否以某个指定的字符串开头
  • boolean isEmpty():判断字符串是否维空。
  • 注:""和null的区别:
    • ""是字符串常量,同时也是一个String类的对象,既然是对象当然可以调用String类中的方法
    • null是空常量,不能调用任何的方法,否则会出现空指针异常,但是null常量可以给任意的引用数据类型赋值。
  1. 常见对象(String类的获取功能)
  • int length():获取字符串长度
int[] arr = {11, 22, 33};
System.out.println(arr.length);// 数组中的length是属性
        
String s1 = "haha";
System.out.println(s1.length());
  • char charAt(int index):获取指定索引位置的字符
  • int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。
  • int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引。
  • int indexOf(int ch, int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。
  • int indexOf(String str, int fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。
  • lastIndexof:从后向前找第一次出现的字符。
  • String substring(int start):从指定位置开始截取字符串,默认到末尾。
  • String substring(int start, int end):从指定位置开始到指定位置结束截取字符串。(左闭右开)
  1. 字符串的遍历
public class Test2_BianliString {
    public static void main(String[] args) {
        String s = "hello";
        for (int i  = 0; i < s.length(); i++ ) {
            System.out.println(s.charAt(i));
        }
    }
}
  1. 统计不同类型字符的个数
public class Test3 {
    public static void main(String[] args) {
        String s = "ABCDEabcd123456!@#$%^";
        int big = 0;
        int small = 0;
        int num = 0;
        int other = 0;
        
        // 1. 判断每个字符,通过for遍历
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            // 2. 判断字符是否在这个范围内
            if (c >= 'A' && c <= 'Z') {
                big ++;
            } else if (c >= 'a' && c <= 'z') {
                small ++;
            } else if (c >= '0' && c <= '9') {
                num ++;
            } else {
                other ++;
            }
        }
        // 3.打印每个计数器的结果
        System.out.println(s + "中大写字母有:" + big + "个,小写字母有:" + small + "个, 数字字符有:"  + num + "个");
    }
}
  1. String类的转换功能
  • byte[] getBytes():把字符串转换为字节数组

  • char[] toCharArray():把字符串转换为字符数组

  • static String valueOf(char[] chs):把字符数组转换为字符串

    • String类的valueOf方法可以把任意类型的数据转成字符串
  • String toLowerCase():把字符串转成小写

  • String toUpperCase():把字符串转成大写

  • String concat(String str):把字符串拼接

public class Demo6_StringMethod {
    public static void main(String[] args) {
        //demo1();
        //demo2();
        //demo3();
        String s1 = "helloWORLD";
        String s2 = "HELLOworld";
        System.out.println(s1.toLowerCase());
        System.out.println(s2.toUpperCase());
    }

    private static void demo3() {
        char[] arr = {'a', 'b', 'c'};
        String s = String.valueOf(arr); // valueOf可以让任意类型数据转换为字符串
        System.out.println(s);

        System.out.println(String.valueOf(100) + 100);
    }

    private static void demo2() {
        String s = "hello";
        char[] arr = s.toCharArray(); // 把字符串转换为字符数组
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    private static void demo1() {
        String s1 = "Aac";
        byte[] arr = s1.getBytes();
        for (int i = 0; i < arr.length; i ++) {
            System.out.print(arr[i] + " ");
        }
    }
}
  1. 常见对象(按要求转换字符)
    需求: 把一个字符串的首字母转换成大写,其余为小写。(只考虑英文大小写字母)
public class Test4 {
    public static void main(String[] args) {
        String s = "heLLoWorlD";
        String s1 = s.substring(0, 1).toUpperCase().concat(s.substring(1).toLowerCase());
        System.out.println(s1);
    }
}
  1. 把数组转换成字符串
    需求:把数组中的数据按照指定格式拼接成一个字符串
  • 举例:
    • 输入: int[] arr = {1, 2, 3};
    • 输出:"[1, 2, 3]"
public class Test5 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        String s = "[";

        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                s = s + arr[i] + "]";
            } else {
                s = s + arr[i] + ", ";
            }
        }
        System.out.println(s);
    }
}
  1. String类的其他功能
  • A: String类的替换功能及案例演示
    • String replace(char old, char new)
    • String replace(String old, String new)
  • B: String的去除字符串两空格及案例演示:
    • String trim()
  • C: String的按字典顺序比较两个字符串及案例演示(了解)
    • int compareTo(String str)
    • int compareToIngnoreCase(String str)
public class Demo7_StringMehtod {
    public static void main(String[] args) {
        //demo1();
        //demo2();
    }

    private static void demo2() {
        String s = "   hel   lo  ";
        System.out.println(s.trim()); // 去除两边空格
    }

    private static void demo1() {
        String s = "hello";
        String s1 = s.replace('l', 'z');
        System.out.println(s1);

        String s2 = s.replace('z', 'k'); // z不存在,保留源字符不改变
        System.out.println(s2);
    }
}
  1. 字符串反转
    字符串反转
import java.util.Scanner;

public class Test6 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String line = sc.nextLine();

        char[] arr = line.toCharArray(); // 将字符串转换为字符数组

        String s = "";
        for (int i = arr.length - 1; i >= 0; i--) { // 倒着遍历字符数组
            s = s + arr[i]; // 拼接成字符串
        }
        System.out.println(s);
    }
}
  1. 常见对象(在长字符串中查找小字符串出现的次数)
    题目:查找在长字符串中查找小字符串出现的次数
    具体代码例子如下:
public class Test7 {
    public static void main(String[] args) {
        // 定义长字符串
        String max = "woaiheima, heimabutongyubaima,wulunheimahaishibaima,zhaodaogongzuojiushihaoma";
        // 定义短字符串
        String min = "heima";

        // 定义计数器变量
        int count = 0;
        // 定义索引
        int index = 0;
        // 定义循环,判断短字符串是否在长字符串中出现
        while((index = max.indexOf(min)) != -1) {
            count ++;
            max = max.substring(index + min.length());
        }
        System.out.println(count);
    }
}
  • 注:本文整理自传智播客视频及其提供文档,手码,若有错误,希望大家指出(轻喷),共同学习。目的是便于个人复习,后来考虑到如果有其他同学也想复习,也想跟大家分享。不过毕竟本文整理自其他资料,若有侵权,请私信联系我,删。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值