常用类的使用方法

2025-10-30 04:04:59

1、使用String对象存储字符串

String s = "Hello World";

String s = new String();

String s = new String("Hello World");

String类位于java.lang包中,具有丰富的方法

计算字符串的长度、比较字符串、连接字符串、提取字符串

2、public class Register {

    public static void main(String[ ] args) {

        Scanner input = new Scanner(System.in);

        String uname,pwd;

        System.out.print("请输入用户名: ");

        uname=input.next();

        System.out.print("请输入密码: ");

        pwd=input.next();

        if( pwd.length()>=6 ){

        System.out.print("注册成功! ");

  }else{

        System.out.print("密码长度不能小于6位!");

    }

}

}

常用类的使用方法

3、public class Login {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String uname,pwd;

        System.out.print("请输入用户名: ");

        uname=input.next();

        System.out.print("请输入密码: ");

        pwd=input.next();

        if( uname.equals("TOM") && pwd.equals("1234567") ){

        System.out.print("登录成功! ");

        }else{

        System.out.print("用户名或密码不匹配,登录失败!");

        }

    }   

}

常用类的使用方法

4、public String substring(int index)//

提取从位置索引开始的字符串部分

public String substring(int beginindex, int endindex)

//

提取beginindex和endindex之间的字符串部分

public String trim()

//

返回一个前后不含任何空格的调用字符串的副本

5、检查文件和邮箱格式

//检查邮箱格式

if (email.indexOf('@') !=- 1 && email.indexOf('.')  >  email.indexOf('@')){

emailCorrect = true;

}else{

System.out.println("Email无效。");

}

//检查Java文件名

int index = fileName.lastIndexOf(".");

if(index!=-1 && index!=0 && 

     fileName.substring(index+1, fileName.length()).equals("java")){   

     fileCorrect = true;

}else{

     System.out.println("文件名无效。");

}

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢