gpt4 book ai didi

java - 如何在java中将用户输入拆分为字符数组或字符串数​​组,然后检查是否回文

转载 作者:行者123 更新时间:2023-12-02 12:10:36 26 4
gpt4 key购买 nike

因此,我正在 Java 编程类(class)中编写一个程序,要求创建一个回文程序。我已经成功地使程序可以通过用户输入的一个单词来干净地运行,但我仍然困惑于如何检查用户单独输入的三个单词。到目前为止,这是我的代码。实验室目标是:单独检查每个单词,看看它是否是回文——如果找到,请将其打印到屏幕上。我必须遵循以下指示:• 要求用户在一行中提供三个回文

• 单独检查每个单词,看看它是否是回文——如果找到,则打印它到屏幕上– 提示:查看 String 的 toCharArray() 方法• 不断询问用户,直到他们提供一组至少包含以下内容的单词:一个回文。

import java.util.Scanner;
public class Palindrome {

private static Scanner scanUserInput;
private static String wordGuess, reverseWord ;
public static void main(String[] args) {
scanUserInput = new Scanner(System.in);
System.out.println("WELCOME TO THE PALINDROME CHECKER!!!");
while(true){
System.out.print("Please enter at least three words to check: ");
wordGuess = scanUserInput.nextLine();
reverseWord = "";

//String[] wordArray = wordGuess.split(","); I tried to use this way to split the inputs but no luck
char[] wordArray = wordGuess.toCharArray();
for(int x=wordArray.length-1;x>=0;x--){
reverseWord = reverseWord+wordArray[x];

}
System.out.println(reverseWord);
if(wordGuess.equalsIgnoreCase(reverseWord))
{
System.out.println("");
System.out.println("You have found a Palindrome!!!");
System.out.println("The Palindrome we found was "+reverseWord);
break;
}
else{
System.out.println("");
System.out.println("You have not entered a Palindrome...");
System.out.println("Please Try again...");

}

}//end of main
}
}

谢谢您的宝贵时间。请给我回复任何对我完成本实验有用的文档或任何其他想法。 enter image description here

最佳答案

您可以使用 split 来实现此目的,并且它会起作用。

String[] wordArray = wordGuess.split(" "); //or .split("<seperator used b/w words>")

现在迭代 wordArray 并分别检查每个单词的回文。在您的代码中,您没有单独检查每个单词

//错误

for(int x=wordArray.length-1;x>=0;x--){
reverseWord = reverseWord+wordArray[x];
}

//修改后的代码

   while(true){
System.out.print("Please enter at least three words to check: ");
wordGuess = scanUserInput.nextLine();

String[] wordArray = wordGuess.split(",");
// char[] wordArray = wordGuess.toCharArray();
for (String word : wordArray) {
reverseWord = "";
for(int x=word.length()-1;x>=0;x--){
reverseWord = reverseWord+word.charAt(x);

}
System.out.println(reverseWord);
if(word.equalsIgnoreCase(reverseWord))
{
System.out.println("");
System.out.println("You have found a Palindrome!!!");
System.out.println("The Palindrome we found was "+reverseWord);
}
else{
System.out.println("");
System.out.println("You have not entered a Palindrome...");
System.out.println("Please Try again...");

}
}


}

关于java - 如何在java中将用户输入拆分为字符数组或字符串数​​组,然后检查是否回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46579428/

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