无法添加字符串长度

时间:2013-12-06 23:07:49

标签: java string

我一直在学习Java,出于某种原因,我对如何将两个字符串加在一起有一个大脑放屁。在程序中,我成功地让程序说明了First和Last名称的长度是独立的。但是我希望程序还说明名称中有多少个字符。

我知道我需要将字符串长度分配给可以一起添加的整数变量,但我现在只是在消隐。

我的源代码如下,谢谢你的帮助!

import java.util.Scanner;

/*
 * //Program Name: stringwk7
 * //Author's Name: MrShiftyEyes
 * //Date: 05-12-2013
 * //Description:  Prompt for a user name; print initials; 
 * //              print out the reverse name, find the length of the names
 */


/**
 *
 * @author MrShiftyEyes
 */
public class stringwk7{

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    // Create first name and last name StringBuffers
    Scanner input = new Scanner(System.in);
    System.out.print("What is your first name? ");
    StringBuffer firstName = new StringBuffer(input.nextLine());
    System.out.print("What is your last name? ");
    StringBuffer lastName = new StringBuffer(input.nextLine());

    // Declare two string variables using StringBuffer variables
    String fName = new String(firstName);
    String lName = new String(lastName);

    // Display the users initials
    System.out.println("Your initials are: " + firstName.charAt(0) + " " + lastName.charAt(0));

    // Displays the user's name in reverse
    System.out.println("Your name in reverse is: " + lastName.reverse() + " " + firstName.reverse());

    // Length of name
    System.out.println("The length of my first name is " + firstName.length());
    System.out.println("The length of my last name is " + lastName.length());

    // Insert a goodbye into the firstName string and display to user
    firstName = firstName.reverse(); // Change firstName back to the initial value
    System.out.println(firstName.insert(0, "See ya later, "));       

    }

}

2 个答案:

答案 0 :(得分:3)

你只是在说名字和姓氏?

int fullNameLength = lastName.length() + firstName.length();
System.out.println("The length of my full name is " + fullNameLength);

答案 1 :(得分:2)

(firstName + lastName).length()