当我将字符串拆分为2个单词并交换它们时,我收到错误

时间:2016-02-16 18:03:56

标签: java

这是我遇到的问题

    System.out.println("Please enter the student's name in the form of Doe, John or Smith, Jane");
    name = keyboard.next();
    int index = name.indexOf(",");
    String firstWord = name.substring(0,index); // Cuts the first word from the string
    int lastIndex = (name.lastIndexOf(","))+1;
    String lastWord = name.substring(lastIndex,name.length());// Cuts the last word of the string
    switchedName = lastWord+" , "+firstWord; 
    return switchedName;

这将返回切换的字符串,但仅当它被输入为Doe时,John如果我在名称之间输入一个空格(例如Doe,John),它将在输入名称后立即崩溃并且它被调用下一行代码只是一个println语句

3 个答案:

答案 0 :(得分:1)

而不是name = keyboard.next();,您应该name = keyboard.nextLine();

答案 1 :(得分:1)

更改

name = keyboard.next();

name = keyboard.nextLine();

next()只返回空格之前的内容。

所以你的Doe,(太空)约翰会把你的一半归还给你

nextLine()返回当前行

答案 2 :(得分:1)

对于输入使用nextLine而不是next来读取空格字符后面的内容。 你没有在instanciation之前创建switchName。

  
    

String switchedName = lastWord +" ," + firstWord;