0
public static void main(String[] args) {    
    Scanner in = new Scanner(System.in);
    System.out.print("Please choose.('e' to encrypt, 'd' to decrypt, 'q' to quit): ");
    String userIn= in.next();
    if(userIn.equals("e")){
        System.out.println("Please enter your text that you want to encrypt: ");
        String userInput = in.nextLine();

        System.out.print("Please enter your shift key(0-25): ");
        int userS = in.nextInt();
        if(userS < 0 || userS > 25){
            System.out.print("Invalid shift key, please enter a valid shift key: ");
            userS = in.nextInt();
        }

在我上面的程序中,代码的以下部分:

System.out.println("Please enter your text that you want to encrypt: ");
                String userInput = in.nextLine();

                System.out.print("Please enter your shift key(0-25): ");

它正在跳过这个userInput,它会在我输入文本之前越过它并要求输入 shift 键。

4

3 回答 3

1

这修复了它(在 Eclipse 中测试):

Scanner in = new Scanner(System.in);
System.out.print("Please choose.('e' to encrypt, 'd' to decrypt, 'q' to quit): ");
String userInput = in.nextLine();
if (userInput.equals("e"))
{
    System.out.println("Please enter your text that you want to encrypt: ");
    userInput = in.nextLine();

    System.out.print("Please enter your shift key(0-25): ");
    int userS = Integer.parseInt(in.nextLine());
    if (userS < 0 || userS > 25)
    {
        System.out.print("Invalid shift key, please enter a valid shift key: ");
        userS = Integer.parseInt(in.nextLine());
    }
}
in.close();

我将您的userIn变量更改为 be userInput,因为我们不需要它;您的next()电话也更改为nextLine()

nextInt()我还把你所有的'都改成了nextLine()'。这将帮助您避免Exception以后发生。

最后,总是Scanner在完成后关闭它以节省系统资源。

于 2013-04-06T19:38:26.020 回答
0

改变:

String userInput = in.nextLine()

in.nextLine(); String userInput = in.nextLine();
于 2013-04-06T19:38:08.663 回答
0

很简单,把你的代码改成

String userInput = in.next();
于 2013-04-06T19:39:04.467 回答