如何在java中有多个字符串?

时间:2014-11-04 21:52:40

标签: java string

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"?

2 个答案:

答案 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