java中用来对比字符串的是 “equals”。
使用方法为
String A = "123456";
String B = "789456";
if (A.equals(B)){
System.out.println("相同");
}else {
System.out.println("错误");
}
思路
创建字符串 input 记录输入字符串,并与设定好的密码 password 作比较,最多三次机会,如果输入正确就 break 出循环,输入错误就使 frequency-- ,(frequency:为次数的意思)若三次输入都失败,就在循环外判断,如果 frequency = 0,则输入次数用完,退出程序。
代码
public class TestDemo {
public static void main(String[] args) {
String password = "123456789";
Scanner scanner = new Scanner(System.in);
System.out.println("请输入密码");
int frequency = 3;
for (int i = 0; i < 3; i++) {
String input = scanner.nextLine();
if (input.equals(password)){
System.out.println("正确");
break;
}else {
frequency--;
System.out.println("有误,请重新输入,还有" + frequency +"次数");
}
}
if (frequency == 0){
System.out.println("输入次数用完,退出");
}
}