Java 菜单循环问题;程序循环太快?

标签 java loops menu

我正在做一项作业,我必须编写一个程序来加密和解密凯撒密码。我遇到问题的部分不是加密或解密,而是另一个要求,即我必须提供一个菜单,以便用户可以选择加密、解密或退出。此外,程序应该不断提示用户,直到用户选择退出。到目前为止我的代码是:

import java.util.*;
public class CaeserShiftTester
{
    public static void main (String[] args)
    {
        Scanner in = new Scanner(System.in);
        String choice = "";

        while (!choice.equalsIgnoreCase("C"))
        {

        System.out.println("\nPlease select an option");
        System.out.println("[A] Encrypt Code");
        System.out.println("[B] Decrypt Code");
        System.out.println("[C] Quit");

        choice = in.next();

        if(choice.equalsIgnoreCase("A"))
        {
            System.out.println("Please enter your key:");

            final int KEY = in.nextInt();
            System.out.println(CaeserShiftEncryption.shiftAlphabet(KEY));

            System.out.println("\nPlease enter your message:");
            String message = in.nextLine();

            System.out.println(CaeserShiftEncryption.encryptCode(message,KEY));


        }

        if(choice.equalsIgnoreCase("C"))
        {
            System.out.println();
        }
    }


    }

}

我的问题是,在“新字母表”打印到屏幕上后,程序循环回到最开始,要求用户选择a、b或c。用户永远没有机会输入要加密的消息。不幸的是,我需要打印生成的新字母表,我想不出这里可能有什么问题。希望大家能帮帮我。

此外,shiftAlphabet 和 encryptCode 方法均具有完整功能。

最佳答案

看看这个网站:http://www.java-made-easy.com/java-scanner.html

特别是

don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers

关于Java 菜单循环问题;程序循环太快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13784521/

相关文章:

javascript - 小折叠三 Angular 形 : how can I create collapsible sections on a webpage?

java - 简化java if语句

loops - Qbasic 突出显示菜单

python - 当不满足条件时中断 if __name__

python - 为什么我不能以这种方式遍历列表列表?

css - 创建 Css 菜单

android - 菜单文本没有出现在我的 Android 菜单中

java - 在android中解析JSON返回null对象

java - Eclipse 中的 Maven + Spring : Unable to find the downloaded Jars

java - 避免java中许多if else语句的最佳方法