【问题标题】:How do I show only the first letters of a string?如何只显示字符串的第一个字母?
【发布时间】:2014-03-01 11:20:26
【问题描述】:

我正在提示用户输入他们的名字和姓氏,但我不知道如何只显示他们的名字和姓氏缩写

import javax.swing.*;
//import java.awt.*;

public class Lab2Program2 {

    public static void main (String [] args) {

    String firstName;
    String lastName;


    firstName = JOptionPane.showInputDialog(null, "What is your first name?");
    lastName = JOptionPane.showInputDialog(null, "What is your last name?");

    JOptionPane.showMessageDialog(null, " Your initials are " + 
                            firstName + " " + lastName);
    }
}

【问题讨论】:

  • 你的意思是只有名字的第一个字母吗?如果不是你想显示多少个字母?
  • 带有子字符串? (substring(0,1))
  • 请尝试一下(我推荐使用String.substring()),然后与具体问题分享您的代码。
  • 如果您需要它的第一个字母,请使用public char charAt(int index) 方法。要获取名字中的第一个字母,请使用 firstName.charAt(0)

标签: java string substring joptionpane


【解决方案1】:

firstName.charAt(0) 返回 0 索引处的 char 值。那是你的 firstName 字符串的第一个字母。

【讨论】:

    【解决方案2】:

    你可以使用chatAt()方法。

    JOptionPane.showMessageDialog(null, 
                "Your initials are " + firstName.charAt(0) + " " + lastName.charAt(0));
    

    【讨论】:

      【解决方案3】:

      如果你想像以前一样显示一个消息框,这应该可以:

      JOptionPane.showMessageDialog(null, 
          "Your initials are " + firstName.substring(0, 1) + " " + lastName.substring(0, 1));
      

      【讨论】:

        猜你喜欢
        • 2022-06-19
        • 2012-07-15
        • 2014-05-30
        • 1970-01-01
        • 2017-01-30
        • 2022-08-23
        • 1970-01-01
        • 2022-01-09
        • 2017-03-10
        相关资源
        最近更新 更多