Scanner input = new Scanner(System.in);
String name;
String school;
int age;
System.out.print("What is your name? ");
name = input.nextLine();
System.out.print("How old are you? ");
age = input.nextInt();
System.out.print("What school do you attend?" );
school = input.nextLine();
System.out.printf("Your name is %s, you are %d years old and attend %s :) "
, name, age, name);
运行:
What is your name? Example
How old are you? 21
What school do you attend?Your name is Example, you are 21 years old and attend Example :) BUILD SUCCESSFUL (total time: 7 seconds)
如何制作字符串" school"?
答案 0 :(得分:3)
更改
, name, age, name);
到
, name, age, school);
此外,您的格式String
不包含换行符
System.out.printf("Your name is %s, you are %d "
+ "years old and attend %s :)%n", name, age, school);
最后,nextInt()
会留下一个尾随换行符,因此您需要阅读
System.out.print("What is your name? ");
name = input.nextLine();
System.out.print("How old are you? ");
age = input.nextInt();
input.nextLine(); // <-- age gets the number. There is one newline left.
System.out.print("What school do you attend?" );
school = input.nextLine();
Scanner.nextLine()
的Javadoc解释了行为,
使此扫描程序超过当前行并返回跳过的输入。此方法返回当前行的其余部分,不包括末尾的任何行分隔符。该位置设置为下一行的开头。
答案 1 :(得分:0)
将您的代码更改为:
age = Integer.parseInt(input.next());
在printf()
中将名称修改为Scool