自动跳过输入

时间:2013-04-06 19:33:16

标签: java

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,它会在我输入文本之前检查转换键。

3 个答案:

答案 0 :(得分: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变量改为userInput,因为我们不需要它;您的next()来电也已更改为nextLine()

我还将所有nextInt()更改为nextLine()。这有助于您稍后避免Exception

最后,在完成后,请务必关闭Scanner以节省系统资源。

答案 1 :(得分:0)

变化:

String userInput = in.nextLine()

in.nextLine(); String userInput = in.nextLine();

答案 2 :(得分:0)

简单,将代码更改为

String userInput = in.next();
相关问题