2 回答
TA贡献1878条经验 获得超4个赞
处理一个字符后获得两个条目的原因是您没有完全阅读包含该字符的行。
具体来说,您keyboard.nextInt();
在上分支和keyboard.next();
下分支中使用。虽然它们分别读取下一个整数和字符,但它们不处理行尾标记。
然后,当您到达循环的顶部时,您调用keyboard.nextLine()
which 处理 int (或字符,在删除所有情况下)之后出现的任何字符,直到行标记结束。使用预期的用户输入,这只是一个空字符串。
要解决此问题,您需要确保keyboard.nextLine()
在仅读取整数或单个字符的情况下通读。
TA贡献1877条经验 获得超1个赞
发生的事情是,while循环的条件是
while (!command.equalsIgnoreCase("quit"))
这在英语中的意思是,只要命令不等于“退出”然后运行这个循环。
在循环内部,命令实际上从未设置为“退出”。例如,如果我将输入字符串指定为“abcde”并要求在位置 1 删除“c”。那么您的逻辑将命令设置为“删除”
command = keyboard.nextLine();
然后将最终值打印为“abde”。现在当循环结束时,命令仍然是“删除”,因此循环再次执行。
一种可能的解决方案是明确询问用户是否要使用 do while 循环重试。也只是一个提示,我看到你使用了 nextInt。建议在下一个 int 之后立即使用 nextLine。看到这个的原因:Java Scanner 不等待用户输入
如果您想运行更多命令,那么如果您明确征得用户同意,这就是您的代码:
public static void main (String[] args) throws java.lang.Exception
{
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
String retry = "";
// While loop
do {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
keyboard.nextLine();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
System.out.println("Do you want to go again?");
retry = keyboard.nextLine();
// Bracket for while loop
}while("yes".equalsIgnoreCase(retry));
}
添加回答
举报