登录
public class Demo03 {
public static void main(String[] args) {
String username = "奥特曼";
String password = "123456";
for (int i = 1; i <= 3; i++) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入账户");
String name = sc.nextLine();
System.out.println("请输入密码");
String pwd = sc.nextLine();
if (name.equals(username) && pwd.equals(password)) {
System.out.println("登录成功");
break;
} else {
if (2 - i == 0) {
System.out.println("你的账户被锁定");
} else {
System.out.println("登录失败,你还有:" + (3 - i) + "次机会");
}
}
}
}
}
遍历字符串
public class Demo04 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String line = sc.nextLine();
for (int i = 0; i <line.length(); i++){
System.out.println(line.charAt(i));
}
}
}
统计字符次数
public class Demo05 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String line = sc.nextLine();
int bigCount = 0;
int smallCount = 0;
int numberCount = 0;
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
if (ch > 'A' && ch < 'Z') {
bigCount++;
} else if (ch > 'a' && ch < 'z') {
smallCount++;
} else if (ch > '0' && ch < '9') {
numberCount++;
}
}
System.out.println("大写字母:" + bigCount + "个");
System.out.println("小写字母:" + smallCount + "个");
System.out.println("数字:" + numberCount + "个");
}
}
字符串反转
public class Demo06 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String line = sc.nextLine();
String s = reverse(line);
System.out.println("s:" + s);
}
public static String reverse(String s) {
String ss = "";
for (int i = s.length() - 1; i >= 0; i--) {
ss += s.charAt(i);
}
return ss;
}
}
StringBuilder字符串拼接
public class Demo07 {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
String s = arrayToString(arr);
System.out.println("s:" + s);
}
public static String arrayToString(int[] arr) {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
sb.append(arr[i]);
} else {
sb.append(arr[i]).append(",");
}
}
sb.append("]");
String s = sb.toString();
return s;
}
}
StringBuilder字符串反转
public class Demo08 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String line = sc.nextLine();
String s = myReverse(line);
System.out.println("s:" + s);
}
public static String myReverse(String s) {
return new StringBuilder(s).reverse().toString();
}
}