【问题标题】:Password checker using do-while loop使用 do-while 循环的密码检查器
【发布时间】:2020-02-29 03:20:18
【问题描述】:

我朋友在我们的编程活动中提出的问题是

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

例子

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

输入一个单词:tart
第一个字符等于它的最后一个字符:tart

输入一个词:樱桃
程序正在终止...

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

【问题讨论】:

  • 所以你有一个任务,去做吧
  • 我们需要看到您至少尝试过
  • 我们没有被教导如何做那些第一个和最后一个字符的事情,我确实尝试寻找不同的方法来解决问题,我被困在 String pass = "cherry" 和我不知道我应该提出什么条件。抱歉,如果您认为它是免费加载的,但我们正在努力。

标签: java loops passwords do-while


【解决方案1】:

你可以这样做:

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

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 2013-02-16
    • 1970-01-01
    • 2021-07-18
    • 2021-12-14
    • 2021-11-23
    相关资源
    最近更新 更多