有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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)

我怎样才能使字符串成为“学校”


共 (2) 个答案

  1. # 1 楼答案

    改变

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

    {a1}的Javadoc解释了该行为

    Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

  2. # 2 楼答案

    将代码更改为:

    age = Integer.parseInt(input.next());
    

    并在printf()中将名称修改为Scool