文章目录
练习1. 用户登录
已知用户名和密码,请用程序实现模拟用户登录。总共给三次机会,登录之后,给出相应的提示
package cn.kox.practice;
import java.util.Scanner;
/**
* @ClassName: codePractice01
* @Author: Kox
* @Data: 2023/1/20
* @Sketch: 练习1,用户登录
*/
public class codePractice01 {
public static void main(String[] args) {
String userName = "kox";
String password = "Kox123";
Scanner sc = new Scanner(System.in);
int count = 3;
while (count > 0) {
System.out.print("输入用户名:");
String user = sc.next();
System.out.print("输入密码:");
String pd = sc.next();
if (user.equals(userName) && pd.equals(password)) {
System.out.printf("欢迎%s, 登录成功!", user);
System.out.println();
break;
} else {
count--;
System.out.printf("登录失败,还有%s次机会", count);
System.out.println();
}
}
}
}
练习2. 遍历字符串
键盘录入一个字符串,使用程序实现在控制台遍历该字符串
package cn.kox.practice;
import java.util.Scanner;
/**
* @ClassName: codePractice02
* @Author: Kox
* @Data: 2023/1/20
* @Sketch: 练习2,遍历字符串
*/
public class codePractice02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
for (int i = 0; i < str.length(); i++) {
System.out.println(str.charAt(i));
}
}
}
练习3. 统计字符串次数
键盘录入一个字符串,统计该字符串中大写字母字符,小写字母字符,数字字符出现的次数(不考虑其他字符)
package cn.kox.practice;
import java.util.Scanner;
/**
* @ClassName: codePractice03
* @Author: Kox
* @Data: 2023/1/20
* @Sketch: 统计字符次数
*/
public class codePractice03 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("输入一个字符:");
String str = sc.next();
int bigCount = 0;
int smallCount = 0;
int numberCount = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'a' && c <= 'z') {
smallCount++;
} else if (c >= 'A' && c <= 'Z') {
bigCount++;
} else if (c >= 48 && c <= 57) {
numberCount++;
}
}
System.out.printf("bigCount;%s, smallCount:%s, numberCount:%s", bigCount, smallCount, numberCount);
}
}
练习4. 字符串拼接
定义一个方法,把 int 数组中的数据按照指定的格式拼接成一个字符串返回,调用该方法,
并在控制台输出结果。例如,数组为 int[] arr = {1,2,3}; ,执行方法后的输出结果为:[1, 2, 3]
package cn.kox.practice;
/**
* @ClassName: codePractice04
* @Author: Kox
* @Data: 2023/1/20
* @Sketch: 练习4,拼接字符串
*/
public class codePractice04 {
public static void main(String[] args) {
int[] arr = {
1, 2, 3 ,4};
System.out.println(arrToString(arr));
}
public static String arrToString(int[] arr) {
if (arr == null) {