输入密钥后为什么我的程序退出

时间:2016-05-30 07:27:45

标签: java

我对此问题感到困惑,无法理解为什么程序总是在我输入第一个数据后退出。如何输入字符串数据?

import java.util.Scanner;
public class Caesar {

    public static String encode(String enc, int offset) {
        offset = offset % 26 + 26;
        StringBuilder encoded = new StringBuilder();
        for (char i : enc.toCharArray()) {
            if (Character.isLetter(i)) {
                if (Character.isUpperCase(i)) {
                    encoded.append((char) ('A' + (i - 'A' + offset) % 26 ));
                } else {
                    encoded.append((char) ('a' + (i - 'a' + offset) % 26 ));
                }
            } else {
                encoded.append(i);
            }
        }
        return encoded.toString();
    }


    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.print("Enter key: ");
        int key = in.nextInt();
        System.out.print("Enter line: ");
        String str = in.nextLine();

        System.out.println( Cipher.encode( str, key ));

    }
}

2 个答案:

答案 0 :(得分:1)

因为当您输入Key时,您还会按<ENTER>键。在继续之前需要消耗此char,因此请尝试

    Scanner in = new Scanner(System.in);
    System.out.print("Enter key: ");
    int key = in.nextInt();
    in.nextLine();
    System.out.print("Enter line: ");
    String str = in.nextLine();

    System.out.println( Cipher.encode( str, key ));

答案 1 :(得分:0)

 Scanner in = new Scanner(System.in);
        System.out.print("Enter key: ");
        int key = in.nextInt();
        System.out.print("Enter line: ");
        if (in.hasNext()) {
            String str = in.nextLine();
        }

或者您可以在while

中获得输入