字符串不可变,它们的值在创建后不能被更改
虽然 String 的值是不可变的,但是它们可以被共享
字符串效果上相当于字符数组( char[] ),但是底层原理是字节数组( byte[] )
用""定义的字符串对象,只要大小写和顺序以及字母相同,则会被认作同一个对象。
今天创建练习类的时候出现了一个问题,就是在一个新包下无法创建class文件的情况。解决办法如下:
按照图片的提示先点击File,进入Project Structure,点击新窗口左侧的Modules标签,选择你想要创建类的包,然后点击Sources,然后Apply,OK。之后就可以发现这个包下可以创建Class文件了。
通过本节学习,自己写了一个用户登陆验证类。代码如下:
import java.util.Scanner;
public class DenL {
public static void main(String[] args) {
String username = "Flander";
String password = "woaini";
for(int i = 0; i<=3; i++){
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名和密码");
String id = sc.nextLine();
String mm = sc.nextLine();
if(id.equals(username) && mm.equals(password)){
System.out.println("登陆成功,欢迎回来");
break;
}else{
if(i == 3){
System.out.println("错误次数过多,你的账号已被锁定");
}else{
System.out.println("用户名或密码错误,请重新输入,你还有"+(2-i)+"次机会");
}
}
}
}
}
字符串长度的获取:字符串对象.length()
字符串索引处的值:字符串对象.charAt(i)
判断大写字母还是小写字母还是数字,条件直接设置成在其对应的范围之内就可以了。(大写字母:ch>=‘A’ && ch<=‘Z’,小写字母: ch>=‘a’ && ch<=‘z’,数字: ch>=‘0’ && ch<=‘9’)
使用StringBuilder的字符串拼接:
public class ZFP {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3};
String S = Pin(arr);
System.out.println(S);
}
public static String Pin(int[] arr){
StringBuilder sc = new StringBuilder();
sc.append("[");
for(int i=0; i<3; i++){
sc.append(arr[i]);
}
sc.append("]");
String s = sc.toString();
return s;
}
}
字符串反转:
import java.util.Scanner;
public class ZFJ {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String SS = Ireserve(line);
System.out.println(SS);
}
public static String Ireserve(String s){
StringBuilder sa = new StringBuilder(s);
sa.reverse();
String ss = sa.toString();
return ss;
}
}