【问题标题】:How to format an output?如何格式化输出?
【发布时间】:2021-09-09 20:12:07
【问题描述】:

(在 Java 中)编写一个接受名称并将其格式化的程序,如下所示: 如果输入是: 约翰·安东尼·布朗

那么输出必须是: 布朗,约翰 A.

这就是我所拥有的

    int mn;
    String input3;
    int fn;
    int ln;
    String firstName;
    String lastName;
    String middleName;
    Scanner scnr = new Scanner(System.in);
    String input = scnr.nextLine();
    fn = input.indexOf(" ");
    firstName = input.substring(0, fn);
    middleName = input.substring(fn+1, input.length());
    mn = middleName.indexOf(" ");
    lastName = input.substring(mn+1, input.length());
    
    System.out.println(lastName + ", " + mn + " " + firstName + ".");
}

我不断尝试不同的东西,得到奇怪的输出,例如“ry A Lee, 1 Mary”。对于输入“Marry A Lee”

我的课上从来没有涉及过这个话题,我很困惑。

【问题讨论】:

  • 您可以使用String[] splited = str.split("\\s+"); 将字符串str 拆分为空格。在您的示例中,splited 将是 {"John", "Anthony", "Brown"}。希望这个提示有帮助:)

标签: java formatting


【解决方案1】:

因为这是作业,所以我会给出代码片段:

首先,使用split()将文本分解为单词:

String[] names = input.split(" ");

然后建立你的结果:

String result = names[2] + ", " + names[0] + ", " + names[1].charAt(0) + ".";

有更优雅的方法,但这种方法可以说是最容易理解的。

你可以通过迎合不同数量的名字变得更花哨。

【讨论】:

    【解决方案2】:

    试试这样的:

    String[] items = input.split(" ");
    
    //if there are three item in items, then it is the pattern you mentioned
    if (items.length == 3) {
        System.out.println(items[2] + "," + items[0] + items[1].charAt(0) + ".");
    }
    

    【讨论】:

      【解决方案3】:
       String firstName,lastName;
         char middleName; 
         Scanner sc = new Scanner(System.in);
          System.out.println("Name: ");
          firstName = sc.next();
          System.out.println("Surname: ");
          lastName = sc.next();
          System.out.println("Middle Name: ");
          middleName = sc.next().charAt(0);
          System.out.printf("%s, %s %s",lastName,firstName,middleName); //formats the output
      

      我将中间名设为字符,因为显示时使用第一个字母

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-14
        • 1970-01-01
        • 2014-02-27
        • 2016-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多