Java:1.登录判断;2.大串中小串的个数;3.字符类型及个数判断;4.String的两种创建方式。

1.登录判断

例:

public class Test {
    
    
    public static void main(String[] args) {
    
    
        String username = "张三";
        String password = "123456";
        int i = 0;
        while (true) {
    
    
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入用户名:");
            String s1 = scanner.nextLine();
            if (s1.equals(username)) {
    
    
                break;
            } else {
    
    
                System.out.println("用户名输入错误!请重新输入:");
            }
        }
        while (i < 3) {
    
    
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入密码:");
            String s2 = scanner.nextLine();
            i++;
            if (s2.equals(password)) {
    
    
                System.out.println("登录成功!");
                break;
            } else {
    
    
                if (3 - i != 0) {
    
    
                    System.out.println("密码错误!请重新输入");
                    System.out.println("还剩" + (3 - i) + "次机会");
                } else {
    
    
                    System.out.println("三次机会已用完!");
                }
            }
        }
    }
}

测试结果为:
(1)
在这里插入图片描述
(2)
在这里插入图片描述

2.大串中小串的个数

例:

public class StringTest {
    
    
    public static void main(String[] args) {
    
    
        String s1 = "abcabcabc";
        int index = s1.indexOf("ab");
        int count = 0;
        while (index != -1) {
    
    
            count++;
            s1 = s1.substring(index + 2);
            index = s1.indexOf("ab");
        }
        System.out.println(count);
    }
}

运行结果为:
在这里插入图片描述

3.字符类型及个数判断

例:

public class CharacterTest {
    
    
    public static void main(String[] args) {
    
    
        String s = "aaabbb111222AAAZZZ";
        int count1 = 0;
        int count2 = 0;
        int count3 = 0;
        for (int i = 0; i < s.length(); i++) {
    
    
            char c = s.charAt(i);
            if (c >= 'A' && c <= 'Z') {
    
    
                count1++;
            } else if (c >= 'a' && c <= 'z') {
    
    
                count2++;
            } else if (c >= '0' && c <= '9') {
    
    
                count3++;
            }
        }
        System.out.println("大写字母有" + count1 + "个");
        System.out.println("小写字母有" + count2 + "个");
        System.out.println("数字有" + count3 + "个");
    }
}

运行结果为:
在这里插入图片描述
4.String的两种创建方式
例:

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

运行结果为:
在这里插入图片描述
内存图为:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45631296/article/details/102828193