【发布时间】: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, "));
}
}
【问题讨论】: