java - 如何重写输入循环以不包含代码重复?

我有以下代码,只要字母是“a”或“b”,它就会继续要求用户输入字母:

import java.util.Scanner;

public class Main
{   
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        
        String letter;
        
        System.out.print("Enter a letter: ");
        letter = scan.nextLine();
        
        while(letter.equals("a") || letter.equals("b"))
        {
            System.out.println("You entered: " + letter);
            
            System.out.print("Enter a letter: ");
            letter = scan.nextLine();
        }
    }
}

但是下面的代码重复了两次:

System.out.print("Enter a letter: ");
letter = scan.nextLine();

有没有办法让上面的代码只出现一次?

最佳答案

    while (true) {
        System.out.print("Enter a letter: ");
        String letter = scan.nextLine();
        if (!letter.equals("a") && !letter.equals("b"))
            break;
        System.out.println("You entered: " + letter);
    }

这是循环的经典示例,它既不是自然的 while-do 也不是 do-while — 如果您想要相同的行为并减少代码重复,它需要从中间退出。

(另请注意,变量声明 letter 已移至内部范围,因为外部范围不再需要它。这是一个积极的小迹象。)

作为 while (true) 的替代方案,某些语言允许使用 for(;;) 中的退化 for 循环。


下面以更多的控制流逻辑为代价颠倒了条件循环退出测试的逻辑。

    while (true) {
        System.out.print("Enter a letter: ");
        String letter = scan.nextLine();
        if (letter.equals("a") || letter.equals("b")) {
            System.out.println("You entered: " + letter);
            continue;
        }
        break;
    }

(它们在效率方面没有区别——它们在机器代码级别是等价的。)

https://stackoverflow.com/questions/72192193/

相关文章:

email - 为什么 CR 和 LF 在电子邮件中一起出现如此重要?

python - python中的快速过滤方法

perl - 如何在 Perl 中将本地时间转换为 Unix 时间戳?

arrays - 在 C 中,是否可以创建没有 '\0(null)' 的字符串?

.net - 如何在 .NET 中替换“

csv - 如何将密码和登录数据导入 firefox?

c++ - assert 语句在 C++ 中不起作用

php - 如何在php中显示x天前的时间

flutter - 为什么 Visual Studio Code 中的代码文本没有颜色?

php - 我可以获取最初在包含文件中调用的 PHP 文件的路径吗?