在字符串中间单词上的字计数器

时间:2014-11-18 20:01:27

标签: string count names

所以我制作了一个程序,它基本上可以找到并打印用户输入的字符串的中间名。我希望程序能够打印中间名,即使有4个名字,例如;进入“约瑟夫阿兰博客”将打印“阿兰”,但也进入“约瑟夫阿兰史蒂文博客”将打印“阿兰史蒂文”

所以这里是我坚持的一点我想要它,以便如果用户输入2个或更少的名称,则会打印一条错误消息,告诉用户输入更多名称但是当前我收到以下错误。

Exception in thread "main" 
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1937)
    at W4T2C.main(W4T2C.java:39)

我的代码如下

 Scanner sc = new Scanner(System.in);
        int count = 0;
        while (count < 2) 
        {
        System.out.print("Enter full name (at least 2 words): ");
        String name = sc.nextLine(); 
        // reads from the keyboard the name entered by the user

            String[] numNames = name.split(" ");
            // splits the string into different arrays by where the spaces are i.e. into the names
            for (int i = 0; i < numNames.length; i++) 
            {
                if (numNames[i].equals(" ")) 
                {
                } 
                else 
                {
                    count++;
                    System.out.println("Please enter 3 names or more");
                    // counts the number of names entered 


        int firstSpace = name.indexOf(" ");
        // finds the index of the first space in the name

        int lastSpace = name.lastIndexOf(" ");
        // finds the index of the last space in the name

        String middleName = "";
        // initially sets the middle name as nothing

               middleName = name.substring(firstSpace + 1, lastSpace);
               // sets the middle name as the set of string in between the index of the 
               // first space plus 1 and the last space i.e. the middle name/names

        System.out.println(middleName);
        // prints the middle name
        break;
    }

先谢谢你们......

1 个答案:

答案 0 :(得分:0)

当用户输入单个名称并且第一个和最后一个索引变得相同时,就会出现错误。我认为您不需要循环来计算。请尝试以下代码:

public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        boolean flag = true;
        while (flag) {
            System.out.print("Enter full name (at least 2 words): ");
            // reads from the keyboard the name entered by the user
            String name = sc.nextLine();
            name = name.trim();
            if (!name.isEmpty()) {
                int firstSpace  = name.indexOf(" ");
                int lastSpace = name.lastIndexOf(" ");
                if (firstSpace != lastSpace) {
                    String middelName = name.substring(firstSpace + 1,
                            lastSpace);
                    System.out.println(middelName);
                    flag = false;
                } else {
                    System.out.println("Please enter 3 names or more");
                }

            }
        }
    }