gpt4 book ai didi

java - 循环后清除java字符串

转载 作者:行者123 更新时间:2023-11-30 07:33:16 25 4
gpt4 key购买 nike

我是Java新手,正在为类创建一个项目,该项目基本上要求用户输入一个字符串,然后测试该字符串并打印它是否是回文(与向前和向后相同......即妈妈)或爸爸或赛车)

我已经让代码可以工作,但是我有一个循环设置来重新运行程序或在最后退出。我的问题是,当您重新运行程序并输入另一个字符串输入时,它会将其添加到原始字符串中。

如何每次重置或删除字符串输入以使其重新开始?

感谢您的帮助!另请注意,可能有更好或更快的方法来完成我在这里所做的事情,但我对 java 的知识有限,而且我才刚刚开始,所以我使用了迄今为止学到的知识。谢谢!!

import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {

String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
String redoAnswer; // answer to rerun program

int length; //length of word entered by user

boolean test;
boolean redo; // boolean to rerun program
boolean exit; // boolean to validate exit/rerun


Scanner scan = new Scanner(System.in);

do {
redo = true;
exit = true;

System.out.println("Please enter a string: ");
input = scan.nextLine();

length = input.length();

for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);

if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {

System.out.println("Sorry, this string is NOT a palindrome!");
}

do {
System.out.println("Please type r to restart or q to quit");
redoAnswer = scan.nextLine().trim().toLowerCase();
if (redoAnswer.equals("r")) {
exit = false;
redo = true;
continue;
} else if (redoAnswer.equals("q")) {
exit = false;
redo = false;
System.out.println("Goodbye!");
continue;
} else {
System.out.println("Sorry, I didn't catch that.");
continue;
}
} while (exit);
} while (redo);
} //end main
} //end class

好的,感谢你们的帮助,我明白了...还重写了代码,这样您就可以继续输入新字符串或输入 q 退出,而不是最后重做问题。希望这更干净!

import java.util.Scanner;
public class Palindrome_Test {
public static void main(String[] args) {
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input

int length; //length of word entered by user

boolean redo = true; // boolean to rerun program

Scanner scan = new Scanner(System.in);

do {
System.out.println("Please enter a string, or type Q to quit: ");
input = scan.nextLine();
if (input.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
redo = false;
} else {
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);

if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
reverse = "";
}
} while (redo);
} //end main
} //end class

最佳答案

在 while 循环末尾添加 reverse = "";

关于java - 循环后清除java字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35762291/

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