Java案例:登陆验证生成随机验证码
package com.domain.hello;
import java.util.Random;
public class Test {
public static void main(String[] args) {
System.out.println(getCode(8));
}
// 生成随机验证码
public static String getCode(int n) {
Random r = new Random();
String code = "";
for (int i = 0; i < n; i++) {
int type = r.nextInt(3);
switch (type) {
case 0:
// Alt + 回车键 强制转换 前面加(char)
// 生成大写字符
char ch = (char) (r.nextInt(26) + 65);
code += ch;
break;
case 1:
// 生成小写字符
char ch2 = (char) (r.nextInt(26) + 97);
code += ch2;
break;
case 2:
code += r.nextInt(10);
break;
}
}
return code;
}
}
package com.domain.string;
import java.util.Random;
/**
练习题:使用String完成随机生成5位的验证码。
*/
public class StringExec6 {
public static void main(String[] args) {
// 1、定义可能出现的字符信息
String datas = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
// 2、循环5次,每次生成一个随机的索引,提取对应的字符连接起来即可
String code = "";
Random r = new Random();
for (int i = 0; i < 5; i++) {
// 随机一个索引
int index = r.nextInt(datas.length());
char c = datas.charAt(index);
code += c;
}
// 3、输出字符串变量即可
System.out.println(code);
}
}
练习题:模拟用户登录
package com.domain.string;
import java.util.Random;
import java.util.Scanner;
/**
练习题:模拟用户登录
*/
public class StringExec7 {
public static void main(String[] args) {
// 1、定义正确的登录名称和密码
String okLoginName = "admin";
String okPassword = "domain";
// 2、定义一个循环,循环3次,让用户登录
Scanner sc = new Scanner(System.in);
for (int i = 1; i <= 3; i++) {
System.out.println("请您输入登录名称:");
String loginName = sc.next();
System.out.println("请您输入登录密码:");
String password = sc.next();
// 3、判断登录是否成功!
if(okLoginName.equals(loginName)){
// 4、判断密码是否正确
if(okPassword.equals(password)){
System.out.println("登录成功!欢迎进入系统随意浏览~~~~");
break;
}else {
// 密码错误了
System.out.println("您的密码不正确!您还剩余" + (3 - i) +"次机会登录!");
}
}else {
System.out.println("您的登录名称不正确!您还剩余" + (3 - i) +"次机会登录!");
}
}
}
}
手机号截取
package com.domain.string;
import java.util.Scanner;
/**
练习题:手机号码屏蔽
*/
public class StringExec8 {
public static void main(String[] args) {
// 1、键盘录入一个手机号码
Scanner sc = new Scanner(System.in);
System.out.println("请您输入您的手机号码:");
String tel = sc.next();
// 2、截取号码的前三位,后四位 18665666520
String before = tel.substring(0, 3); // 0 1 2
String after = tel.substring(7); // 从索引7开始截取到手机号码的末尾
String s = before + "****" + after;
System.out.println(s);
}
}
