为什么我不把输入作为下面程序的字符串输入

时间:2015-11-27 01:13:39

标签: java

Scanner keyboard = new Scanner(System.in);
//prompt the user input for a number
int a  = keyboard.nextInt();
//prompt the user input for a string
String str = keyboard.nextLine();

获取字符串输入

1 个答案:

答案 0 :(得分:0)

.nextLine()正在获得' \ n'字符尾随整数。通过在keyboard.nextLine()之后添加.nextInt()来解决此问题。如下:

Scanner keyboard = new Scanner(System.in);
// prompt the user input for a number
int a  = keyboard.nextInt();
// prompt the user input for a string
keyboard.nextLine(); // This captures the '\n' character trailing the integer
String str = keyboard.nextLine();