java - 使用 do-while 循环的密码检查器
问题描述
我朋友在我们的编程活动中提出的问题是
编写一段代码,从键盘读取单词,直到输入单词“cherry”或“CHERRY”。对于除 done 之外的每个单词,报告其第一个字符是否等于其最后一个字符。对于所需的循环,使用 do-while 语句。
例子
输入一个单词:mart
第一个字符不等于它的最后一个字符:mart
输入一个单词:tart
第一个字符等于它的最后一个字符:tart
输入一个词:cherry
程序正在终止...
package liniper;
import java.util.Scanner;
public class Liniper {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String pass = "cherry";
do{
System.out.println("Enter a word: ");
pass = in.nextLine();
} while("cherry".equal(pass))
}
}
解决方案
你可以这样做:
public static void main(String[] args) {
final String pass = "cherry"; // Defining the pass variable
String word; // Defining the word variable
boolean running = true; // Defining the running variable
Scanner scanner = new Scanner(System.in); // Making new Scanner Instance
do {
System.out.print("Enter a word: "); // Informing the User to enter a word
word = scanner.nextLine(); // Retrieving the Word from Input
char first = word.charAt(0); // Get the first character of the word by using the #charAt(int) method
char last = word.charAt(word.length() - 1); // Get the second character by looking at the total length of the word and subtracting 1
// Make the word lowercase and see if it matches the "pass" variable we defined
if (word.toLowerCase().equals(pass)) {
running = false; // Stop the loop
System.out.println("The program is now terminating..."); // Informing the user that the program stops
// Checking if the first character equals the last
} else if (first == last) {
// Informing the user that the first character is equal to the last last character
System.out.println("The first character is equal to it's last character:" + word);
} else {
// Informing the user that the first character is not equal to the last last character
System.out.println("The first character is not equal to it's last character:" + word);
}
} while (running);
}
我希望这可以帮助你。
推荐阅读
- java - ArrayList 方法导致生产者消费者死锁
- php - PHP - Symfony 4 - API 平台 - 自定义操作
- mysql - 错误 - XAMPP - MySQL 意外关闭
- php - 来自嵌套列表字符串的漂亮打印树图
- php - PHP MYSQL 显示表 a 中的所有值,但仅显示表 b 中的匹配值,其中表 b 是单独的循环
- android - Firebase UI 回收器视图适配器 onDataChanged 获取对已更改数据的引用
- sql - 具有多列顺序时的 CASE 表达式
- javascript - 角度js滚动指令不起作用
- listview - Flutter:在 ListView 中动画项目删除
- dart - 在 TextFormField Flutter 中使用 FocusNode