[英]Why my program exit after I enter the key
我对这个问题感到困惑,无法理解为什么输入第一个数据后总是退出程序。 如何输入字符串数据?
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 ));
}
}
因为当您输入Key
您还要按下<ENTER>
键。 需要先消耗掉此字符,然后再尝试
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 ));
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
获得输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.