gpt4 book ai didi

java - 逻辑错误导致语句在 While 循环中打印两次

转载 作者:行者123 更新时间:2023-12-02 01:37:46 25 4
gpt4 key购买 nike

所以我当前遇到的问题是,在我完成所有步骤后,语句“输入您的命令(反向,首先替换,最后替换,全部删除,删除)”打印了两次。

我相信正在发生的是循环执行了两次,但我不知道为什么。任何帮助解决这个问题将不胜感激。如果我的代码格式不好,请提前抱歉,仍在学习如何正确格式化。

import java.util.Scanner;

public class StringChangerenter {
public static void main(String[] args) {
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 = "";

// While loop
while (!command.equalsIgnoreCase("quit")) {
// 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();
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);
}
// Bracket for while loop
}
}
}

最佳答案

处理完一个字符后,您收到两个条目的原因是您尚未完全阅读包含该字符的行。

具体来说,您在上部分支中使用 keyboard.nextInt(); ,在下部分支中使用 keyboard.next(); 。虽然它们分别读取下一个整数和字符,但它们不处理行尾标记。

然后,当到达循环顶部时,调用 keyboard.nextLine() 来处理 int (或字符,在删除所有情况下)之后出现的任何字符,直到行尾标记。对于预期的用户输入,这只是一个空字符串。

要解决此问题,您需要确保在仅读取整数或单个字符的情况下完整读取 keyboard.nextLine()

关于java - 逻辑错误导致语句在 While 循环中打印两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54974833/

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