问题我写了一个程序,提示用户输入他/她的全名首先,中,最后一次。我试图通过在字符串中定位每个空格来使用子字符串方法将该名称分解为三个单独的部分。一旦找到每个空格,名称的以下部分将存储在新的字符串变量中。与Java子方法
我遇到的问题是,中间名是存储中间和最后一个,因为计数器没有正确停止,因为你会看到我的下面的代码,所以我的问题是我该如何解决这个问题。
请注意,我不想分割字符串,我不想使用StringTokenizer的,我不想使用数组,我已经知道如何做到这一点的方式。所有我需要知道的是如何修复我的柜台,我试图做会以这种方式工作,我不是在寻找一种新的方式来做到这一点;我只使用substring和charAt。
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
String name = "",
firstName = "",
middleName = "",
lastName = "";
Scanner in = new Scanner(System.in);
System.out.print("Please enter your name 'First Middle Last': ");
name = in.nextLine();
int i = 0;
while(i < name.length())
{
if(name.charAt(i) == ' ')
{
firstName = name.substring(0, i); // Starts at 0 ends at first occurence of ' '
/* middleName = name.substring(i + 1, i); Should start at i + 1,
or one postion after the previously located white space and
then end at the next occurence of ' '
^The above does not work, and this is where the issue is
happening, how ever if I do the following */
middleName = name.substring(i + 1, name.length());
/* This does work but because the endIndex is name.length() it
runs the length of name and grabs both the middle and last name.*/
i = name.length();
}
++i;
}
System.out.print("\nDisplayed with last name first: " + "\nLast Name: " + lastName + "\nFisrt Name: " + firstName + "\nMiddle Name: " + middleName);
}
}
这会产生输出看起来像这样
Please enter your name 'First Middle Last': First Middle Last
Displayed with last name first:
Last Name:
First Name: First
Middle Name: Middle Last
正如你所看到的第一个名字是正确显示。 中间名是不是因为它包括了“最后”,而不只是“中等”
请考虑[谜底使用比什么是问其他不同的技术(http://meta.stackoverflow.com/questions/268190/answers-that-use-a-different-technology值-than - 什么 - 是 - 问/ 268228#268228)。 – ChiefTwoPencils