Andrew Andrew - 6 months ago 11
Java Question

Why my program exit after I enter the key

I am confused about this problem, cannot understand why the program always exited after I enter the first data. How to enter the String data?

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 ));

}
}

Answer

Because when you enter the Key you also push the <ENTER> key. This char needs to be consumed before continuing, so try

    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 ));