我有一个程序,它是一个回文检查器,它接受输入,反转它,并检查原始输入是否等于反向输入。我试图在程序中得到一个y/n循环,以检查用户是否想输入另一个回文。这是我的密码:
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String controller = "y";
do {
System.out.println("Enter a palindrome!");
String input = scan.nextLine();
String original = input;
input = input.replaceAll("\\s", "");
int len = input.length();
char[] charArray = new char[len];
char[] charArray2 = new char[len];
for(int i = 0; i < len; i++){
charArray2[i] = input.charAt(i);
}
for(int j = 0; j < len; j++){
charArray[j] = charArray2[len-1-j];
}
String palindrome = new String(charArray);
if(palindrome.equals(input)){
System.out.println(palindrome);
System.out.println(original + " is a palindrome!\nWould you like to test another palindrome? (y/n)");
}else{
System.out.println(palindrome);
System.out.println(original + " is not a palindrome!\nWould you like to test another palindrome? (y/n)");
}
scan.next(controller);
}while(controller.equalsIgnoreCase("y"));
}这是我得到的输出:
Enter a palindrome!
was it a cat i saw
wasitacatisaw
was it a cat i saw is a palindrome!
Would you like to test another palindrome? (y/n)
y
Enter a palindrome!
is a palindrome!
Would you like to test another palindrome? (y/n)
y
Enter a palindrome!
is a palindrome!
Would you like to test another palindrome? (y/n)
y
Enter a palindrome!
is a palindrome!
Would you like to test another palindrome? (y/n)
y
Enter a palindrome!
is a palindrome!
Would you like to test another palindrome? (y/n)
y
Enter a palindrome!
is a palindrome!
Would you like to test another palindrome? (y/n)
y我不知道如何让它等待另一个条目,而不是测试它。任何帮助都会很好。
发布于 2020-10-14 00:07:15
好的,我对你的代码做了一些修改,而且你离我不远。这是一个pastebin链接和我的代码。
public static void main(String[] args) {
String checker = "y"; //set checker to ensure the first cycle
while(checker.equalsIgnoreCase("y")) { // check for correct phrase
System.out.println("Enter a string to check!"); // inital message
Scanner reader = new Scanner(System.in); // read first line
String input = reader.nextLine();
if (isPalindrome(input)) { // check input for palindrome
System.out.println(input + " is a Palindrome!");
} else {
System.out.println(input + " is not a Palindrome!");
}
System.out.println("Do you want to enter another string? y/n");
checker = reader.nextLine(); // set checker to response for next cycle
}
System.out.println("Ok bye :)"); // death message
}
private static boolean isPalindrome(String s){
String reverse = ""; // create string for later comparison
for (int i = 0; i < s.length(); i++) {
reverse+=s.trim().charAt(s.length()-i-1); // reverse the string
}
return reverse.equalsIgnoreCase(s); // return boolean ignoring case
}我真的没有改变那么多:
编辑:我的输出:
Enter a string to check!
hey
hey is not a Palindrome!
Do you want to enter another string? y/n
y
Enter a string to check!
brb
brb is a Palindrome!
Do you want to enter another string? y/n
n
Ok bye :)
Process finished with exit code 0https://stackoverflow.com/questions/64344317
复制相似问题