How do I show only the first letters of a string?

馋奶兔 提交于 2019-12-20 08:15:11

问题


I'm prompting the user to enter their first and last name but I can't figure out how to show just their first and last initials

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

回答1:


If you want to show a message box like you were doing before, this should work:

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



回答2:


You can use chatAt() method.

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



回答3:


firstName.charAt(0) returns the char value at the 0 index. That is the first letter of your firstName String.



来源:https://stackoverflow.com/questions/21570278/how-do-i-show-only-the-first-letters-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!