gpt4 book ai didi

java - 当我将字符串拆分为 2 个单词并交换它们时出现错误

转载 作者:行者123 更新时间:2023-12-01 21:49:22 24 4
gpt4 key购买 nike

这是我遇到的问题

    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 语句

最佳答案

您应该执行 name = Keyboard.nextLine(); 而不是 name = Keyboard.next();

关于java - 当我将字符串拆分为 2 个单词并交换它们时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35439898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com