使用do-while循环的密码检查器

时间:2019-11-03 17:25:28

标签: java loops passwords do-while

在我们的编程活动中,我朋友给的问题是

编写一段代码,该代码段将从键盘读取单词,直到最后输入单词“ cherry”或“ CHERRY”。对于除完成之外的每个单词,报告其拳头字符是否等于其最后一个字符。对于必需的循环,请使用do-while语句。

示例

输入一个单词:mart
第一个字符不等于最后一个字符:mart

输入单词: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))
    } 
}

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

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);
}

希望这对您有所帮助。