【问题标题】:Trouble Adding String Length添加字符串长度时遇到问题
【发布时间】:2013-12-06 23:07:48
【问题描述】:

我一直在学习 Java,但出于某种原因,我对如何将两个字符串相加一头雾水。在程序中,我成功地让程序说明名字和姓氏的长度分别是多少。但是我想让程序也说明名称中有多少个字符。

我知道我需要将字符串长度分配给一个可以相加的整数变量,但我现在只是空白。

我的源码如下,谢谢大家的帮助!

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, "));       

    }

}

【问题讨论】:

    标签: java string


    【解决方案1】:

    你只是说名字和姓氏在一起吗?

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

    【讨论】:

    • 感谢您的帮助乔希!我脑子里放了个屁!一定是剩下的感恩节火鸡还在处理中。感谢您的帮助。看到人们在这里回答问题的速度如此之快以及他们总是愿意提供帮助,我总是感到非常惊讶!
    【解决方案2】:
    (firstName + lastName).length()
    

    【讨论】:

    • 请注意,这会分配一个带有后备字符数组的新字符串对象,然后将两个字符串的内容复制到后备数组,然后返回新字符串的长度,然后将立即可用于垃圾收集。虽然在这种情况下所有这些都无关紧要,但我仍然建议改为使用firstName.length() + lastName.length()
    • 我喜欢在上下文中编码。如果它是程序的瓶颈,那么您的观点是正确的,但是,在这种情况下,它是预优化。
    • 这真的很有趣。由于我基本上仍在学习基础知识,因此我期待学习如何优化代码。谢谢你们的帮助!
    猜你喜欢
    • 2013-01-15
    • 2012-04-07
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    相关资源
    最近更新 更多