java常用类---Scanner类和String类

本文详细介绍了 Java 中 Scanner 类的使用方法,包括构造方法、hasNextXxx 和 nextXxx 方法,以及解决常见问题的策略。同时,深入探讨了 String 类的特点,构造方法,判断、获取、遍历、统计、转换功能,以及其他实用功能,如替换、去除空格、比较、反转等,并提供了丰富的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Scanner类

  • A:Scanner的概述: JDK5以后用于获取用户的键盘输入
  • B:Scanner的构造方法原理
    Scanner(InputStream source)
    System类下有一个静态的字段:
    public static final InputStream in; 标准的输入流,对应着键盘录入。

1.1Scanner类的hasNextXxx()和nextXxx()方法

  • 基本格式
    hasNextXxx() 判断下一个是否是某种类型的元素,其中Xxx可以是Int,Double等。
    如果需要判断是否包含下一个字符串,则可以省略Xxx
public class ScannerDemo3 {
    public static void main(String[] args) {

        while (true){
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入一个整数");
            //hasXXX 判断录入数据的 类型
            if (scanner.hasNextInt()) {
                int i = scanner.nextInt();
                System.out.println(i);
                break;
            } else {
                System.out.println("录入类型不正确,请重新输入一个整数");
            }
        }

    }
}

nextXxx() 获取下一个输入项。Xxx的含义和上个方法中的Xxx相同

public class ScannerDemo {
    public static void main(String[] args) {
        InputStream in = System.in;
       // in “标准”输入流。此流已打开并准备提供输入数据。通常,此流对应于键盘输入
        Scanner scanner = new Scanner(in);
        System.out.println("请录入一个整数");
        int i = scanner.nextInt();
        System.out.println(i);
        scanner = new Scanner(in); //重写创建一个对象
        System.out.println("请随便输入一段字符串");
        //录入字符串
        String s = scanner.nextLine();
        System.out.println(s);

        //使用nextLine()方法时,你先录入整数,在录入字符串,会导致字符串录入不进去,你可以再录入字符串时,重新再创建一个Scanner 对象

    }
}

1.2Scanner获取数据出现的小问题及解决方案

  • A:两个常用的方法:
    public int nextInt():获取一个int类型的值
    public String nextLine():获取一个String类型的值
    public String next():获取一个String类型的值
  • B:案例演示
    a:先演示获取多个int值,多个String值的情况
    b:再演示先获取int值,然后获取String值出现问题
    c:问题解决方案
    第一种:先获取一个数值后,在创建一个新的键盘录入对象获取字符串。
    第二种:把所有的数据都先按照字符串获取,然后要什么,你就对应的转换为什么。(后面讲)
public class ScannerDemo2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个整数");
        int i = scanner.nextInt();
        System.out.println(i);
        scanner = new Scanner(System.in);
        System.out.println("请录入一个字符串");
        String s = scanner.nextLine();
       // String s = scanner.next(); 录入的字符串中间,有空格,空格后面的内容不录入
        System.out.println(s);
    }
}

2.String类

  • A:什么是字符串
    字符串是由多个字符组成的一串数据==(字符序列)==
    字符串可以看成是字符数组
  • B:String类的概述
    a:字符串字面值"abc"也可以看成是一个字符串对象。
    b:字符串是常量,一旦被创建,就不能被改变。

2.1String类的构造方法

  • 常见构造方法
    public String():空构造
    public String(String original):把字符串常量值转成字符串
    public String(byte[] bytes):把字节数组转成字符串
    public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串(index:表示的是从第几个索引开始, length表示的是长度)
    public String(char[] value):把字符数组转成字符串
    public String(char[] value,int index,int count):把字符数组的一部分转成字符串

public int length():返回此字符串的长度。

2.2String的特点一旦被创建就不能改变

  • A:String的特点: 一旦被创建就不能改变 因为字符串的值是在方法区的常量池中划分空间 分配地址值的
  • B:案例演示
    a:如何理解这句话
    String s = “hello” ;
    s = “world” + “java”; 问s的结果是多少?
    b:画内存图解释: 内容不能变,引用可以变

在这里插入图片描述

2.3String类的常见面试题

  • A:面试题1
    "=="和equals()的区别?
    == 号可以比较基本数据类型,也可以比较引用数据类型
    equals方法只能比较引用数据类型,默认比较的是地址值,如果我们想要建立自己的比较方式,我们就需要复写equals方法
  • B:面试题2
    看程序写结果
	public class MyTest3 {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        System.out.println(s1 == s2);
        System.out.println(s1.equals(s2));

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

        String s5 = "hello";
        String s6 = "hello";
        System.out.println(s5 == s6);
        System.out.println(s5.equals(s6));
    }
}
/*
结果:
false
true
false
true
true
true
*/

2.4String类的判断功能

public boolean equals(Object obj): 比较字符串的内容是否相同,区分大小写
public boolean equalsIgnoreCase(String str): 比较字符串的内容是否相同,忽略大小写
public boolean contains(String str): 判断字符串中是否包含传递进来的字符串
public boolean startsWith(String str): 判断字符串是否以传递进来的字符串开头
public boolean endsWith(String str): 判断字符串是否以传递进来的字符串结尾
public boolean isEmpty(): 判断字符串的内容是否为空串""。

public class MyTest {
    public static void main(String[] args) {
        //与判断相关的方法
        boolean b = "abc".equals("abc"); //区分大小写
        System.out.println(b);
        boolean b1 = "ABC".equalsIgnoreCase("abc");//不区分大小写
        System.out.println(b1);
        //判断一个字符串中是否包含这个子串
        boolean b2 = "完后余生,洗衣是你,做饭是你,带娃还是你".contains("是你");
        System.out.println(b2);

        //判断是否以这个字符串开头或结尾
        System.out.println("abc".startsWith("a"));
        System.out.println("abc".endsWith("c"));

        //判断是否是空串
        System.out.println("".isEmpty());
        System.out.println("".length() == 0);


    }
}

2.5常见对象☞模拟用户登录

public class MyTest2 {
    public static void main(String[] args) {
       /* A:
        案例演示:
        需求:模拟登录, 给三次机会, 并提示还有几次。
        */

        //模拟从数据库查出来的数据
        String name = "张三";
        String password = "123456";


        //给三次机会 ,提示剩余次数
        for (int i = 1; i <= 3; i++) {

            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入你的用户名");
            String uname = scanner.nextLine();

            System.out.println("请输入你的密码");
            String pwd = scanner.nextLine();
            if (uname.equals(name) && pwd.equals(password)) {
                System.out.println("登录成功");
                //取款
                break;
            } else {
                if ((3 - i) == 0) {
                    System.out.println("3次机会已经用完,你的卡已被回收.");

                } else {
                    System.out.println("用户名或密码输入错误,请重新输入,你还剩余" + (3 - i) + "次机会");
                }

            }
        }



    }
}

2.6String类的获取功能

public int length(): 获取字符串的长度。
public char charAt(int index): 获取指定索引位置的字符
public int indexOf(int ch): 返回指定字符在此字符串中第一次出现处的索引。
public int indexOf(String str): 返回指定字符串在此字符串中第一次出现处的索引。
public int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。
public int indexOf(String str,int fromIndex): 返回指定字符串在此字符串中从指定位置后第一次出现处的索引。
可以顺带提一下lastIndexOf系列
public String substring(int start): 从指定位置开始截取字符串,默认到末尾。
public String substring(int start,int end): 从指定位置开始到指定位置结束截取字符串。

public class MyTest2 {
    public static void main(String[] args) {
        //有关于获取的方法
        int length = "这是一个字符串".length(); //获取长度


        //字符串编有索引
        //indexOf() 查找该字符或字符串,在原串中第一次出现的索引
        int index = "这是一个字符串是".indexOf('是');
        //如果没有找到 返回 -1 我们经常用这个作为判断依据
        index = "这是一个字符串是".indexOf("字符串2");

        System.out.println(index);
        //charAt(6) 根据索引截取单个字符
        char ch = "这是一个字符串是".charAt(6);
        System.out.println(ch);
        String s = "这是一是个是字符是串是";

        ch = s.charAt(s.indexOf("字"));

        System.out.println(ch);

        //从后往前检索
        int index1 = s.lastIndexOf("是");
        System.out.println(index1);
        //可以指定开始的地方来检索

        int index2 = s.indexOf('是', s.indexOf('个'));
        System.out.println(index2);

        //从原串中截取一段字串

        String str = "假如我年少有为不自卑,懂得什么是珍贵";
        //根据起始索引截取到末尾
        String s1 = str.substring(str.indexOf("懂"));
        System.out.println(s1);

        //根据首尾索引,截取一部分字符串
        String s2 = str.substring(3, str.indexOf('卑')+1); //含头不含尾部
        System.out.println(s2);
    }
}

2.7字符串的遍历

public class MyTest3 {
    public static void main(String[] args) {
        String str = "假如我年少有为不自卑,懂得什么是珍贵";
       // char c = str.charAt(0);
        //遍历字符串
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            System.out.println(c);
        }

    }
}

2.8统计不同类型字符个数

public class MyTest4 {
    public static void main(String[] args) {
        /*A:
        案例演示:
        需求:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)*/
        String str="asfdassdfASFSsf1222asdfas5555s4555AFFDDdddaAAA";
        //遍历字符串
        int num=0;
        int da=0;
        int xiao=0;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if(ch>='a'&&ch<='z'){
                xiao++;
            }else if(ch >= 'A' && ch <= 'Z'){
                da++;
            } else{
                num++;
            }
        }

        System.out.println("大写字母"+da+"个");
        System.out.println("小写字母" +xiao+ "个");
        System.out.println("数字字符" + num + "个");

    }
}

2.9String类的转换功能

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 MyTest {
    public static void main(String[] args) {
        //转换功能相关的方法
        //转换大小写
        String s = "abcd".toUpperCase();
        System.out.println(s);
        String s1 = "AAAA".toLowerCase();
        System.out.println(s1);

        //把字符串转换成字节数组
        byte[] bytes = "abcd".getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
        }
        System.out.println(bytes.length);
        //把字节数组转换成字符串
        String s2 = new String(bytes, 0, bytes.length);
        System.out.println(s2);

        System.out.println("-----------------------------");
        //把字符串转换成字节数组
        byte[] bytes1 = "我在人民广场吃着炸鸡".getBytes();
        System.out.println(bytes1.length);//
        for (int i = 0; i < bytes1.length; i++) {
            System.out.println(bytes1[i]);
        }
        //把字节数组转换成字符串
        String s3 = new String(bytes1, 6, 15);
        System.out.println(s3);

        //UTF-8 一个汉字占3个字节

       // System.out.println("錒".getBytes().length);

        //把字符串转换成字符数组
        String s4="我在人民广场吃着炸鸡";
        /*
        char[] chars = new char[s4.length()];
        for (int i = 0; i < s4.length(); i++) {
            chars[i]=s4.charAt(i);
        }

         */

        char[] chars = s4.toCharArray();

        //把一个字符数组转换成字符串
        String s5 = new String(chars);
        System.out.println(s5);

        String concat = "abc".concat("aaa").concat("ccc").concat("dddd");
        System.out.println(concat);


    }
}

2.10按要求转换字符

需求:把一个字符串的首字母转成大写,其余为小写。(只考虑英文大小写字母字符)

public class MyTest2 {
    public static void main(String[] args) {
     /*   A:
        案例演示:
        需求:把一个字符串的首字母转成大写,其余为小写。(只考虑英文大小写字母字符)*/
        String s = "caBDfdaaffdfeadfeafdFAAFF";
        //链式编程
        String concat = s.substring(0, 1).toUpperCase().concat(s.substring(1).toLowerCase());
        System.out.println(concat);

        char ch='A'+32;  //
        System.out.println(ch);

    }
}

2.11String类的其他功能

  • A:String的替换功能及案例演示
    public String replace(char old,char new) 将指定字符进行互换
    public String replace(String old,String new) 将指定字符串进行互换
  • B:String的去除字符串两空格及案例演示
    public String trim() 去除两端空格
public class MyTest {
    public static void main(String[] args) {
        String str="奥巴马和特朗普是美国总统";
        //一次替换一个字符
        String s = str.replace('奥', '*');
        System.out.println(s);

        String s1 = str.replace("奥巴马", "***");
        System.out.println(s1);

        String s2 = str.replace("奥巴马", "***").replace("特朗普", "####");
        System.out.println(s2);
        //去除两端空格
        String username="     zhangsan     ";
        String s3 = username.trim();
        System.out.println(s3);
    }
}
  • C:String的按字典顺序比较两个字符串及案例演示
    public int compareTo(String str) 会对照ASCII 码表 从第一个字母进行减法运算 返回的就是这个减法的结果
    如果前面几个字母一样会根据两个字符串的长度进行减法运算返回的就是这个减法的结果
    如果连个字符串一摸一样 返回的就是0
    public int compareToIgnoreCase(String str) 跟上面一样 只是忽略大小写的比较
public class MyTest2 {
    public static void main(String[] args) {
        String str="abc";
        String str2="abcdef";
        boolean b = str.equals(str2);
       // str.equalsIgnoreCase(str) 不区分大小写的比较

        //比较两个字符串 按照字典顺序去比,返回的是两个字符的差值
        //当字典顺序比不出来,用长度去比
        int num = str.compareTo(str2);
        if(num==0){

        }

      //  str.compareToIgnoreCase(str2) 不区分大小写的比较
        System.out.println(num);
    }
}

2.12把数组转成字符串

public class MyTest3 {
    public static void main(String[] args) {
       /* A:
        案例演示
        需求:把数组中的数据按照指定个格式拼接成一个字符串
        举例:
        int[] arr = {1, 2, 3};
        拼接结果:
        "[1, 2, 3]"*/

        int[] arr = {1, 2, 3,4,5};
        //对上面的数组,进行遍历,经过你的处理得到一个漂亮的字符串
        //"[1,2,3]";
        String str="[";
        for (int i = 0; i < arr.length; i++) {
            if(i==arr.length-1){
                str+=arr[i]+"]";
            }else{
                str+=arr[i]+",";
            }
        }
        System.out.println(str);
    }
}

2.13字符串反转

public class MyTest {
    public static void main(String[] args) {
        /*A:
        案例演示
        需求:把字符串反转
        举例:键盘录入 "abc"
        反转结果:"cba"*/
        Scanner scanner = new Scanner(System.in);
        System.out.println("请随便输入一段字符串");
        String s = scanner.nextLine(); //你爱我
        String str="";
        for (int i = s.length()-1; i >=0; i--) {
            char c = s.charAt(i);
            str+=c;
        }
        System.out.println(str);
    }
}

2.14在大串中查找小串出现的次数

需求:统计大串中小串出现的次数
举例: "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun”中java出现了5次

	public class MyTest2 {
    public static void main(String[] args) {
        String maxStr = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
        //其他办法
        //替换:把java替换成一个特殊字符,统计这个特殊字符
        int count=0;
        if(!maxStr.contains("#")){
            String string = maxStr.replace("java", "#");
            for (int i = 0; i < string.length(); i++) {
                char c = string.charAt(i);
                if(c=='#'){
                    count++;
                }
            }
        }

        System.out.println("java出现了" + count + "次");

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值