如何只显示字符串的第一个字母?

时间:2014-02-05 06:39:50

标签: java string substring joptionpane

我提示用户输入他们的名字和姓氏,但我无法弄清楚如何只显示他们的第一个和最后一个首字母

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);
    }
}

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您可以使用chatAt()方法。

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

答案 2 :(得分:0)

firstName.charAt(0)返回0索引处的char值。这是firstName String的第一个字母。