这是我正在处理的程序,但是我在弄清楚如何通过说出一个单词或数字来询问用户是否完成了这个程序时遇到了问题。
import java.util.Scanner;
class paliindrome {
public static void main(String args[]) {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
PalindromeChecker aGame = new PalindromeChecker();
System.out.println(" Please type a word and I'll figure out if it's a palindrome(The program is case sensitive).");
isPalindrome = in.nextLine();
int length = isPalindrome.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + isPalindrome.charAt(i);
if (isPalindrome.equals(reverse))
System.out.println("The word that you have entered is a palindrome.");
else
System.out.println("The word that you have typed isn't a palindrome.");
char answer;
do {
aGame.play ();
System.out.print("\n Do you want to continue (y or n)?");
answer = keyboard.next().charAt(0);
} while (answer == 'y' || answer == 'Y');
}
}
答案 0 :(得分:1)
将整个应用程序放在循环中。一种简单的方法是将answer
默认为y
(并且您可以使用Character.toUpperCase(char)
来消除or或类似
PalindromeChecker aGame = new PalindromeChecker();
char answer = 'y';
while (Character.toUpperCase(answer) == 'Y') {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
// ... The rest of your code ...
aGame.play();
System.out.print("\n Do you want to continue (y or n)?");
answer = keyboard.next().charAt(0);
}
答案 1 :(得分:0)
还有一种方法可以解决您的问题:
将整个代码置于无限循环中,如此while(true)
,在循环退出前的最后一行循环中,您可以询问用户是否要继续。如果回答是肯定的,那么使用代码System.exit(0)
退出程序,或者如果您想在循环中断开,请在if条件中使用break;
。
答案 2 :(得分:0)
You can use below code to ask user for quit.
boolean quit = false;
Scanner scanner = null;
try {
do {
System.out.println("Do you want to quit? (true/false)\n");
scanner = new Scanner(System.in);
String input = scanner.nextLine();
quit = Boolean.parseBoolean(input);
} while (!quit);
} finally {
scanner.close();
}
答案 3 :(得分:0)
import java.util.Scanner;
public class paliindrome {
public static void main(String[] args) {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
PalindromeChecker aGame = new PalindromeChecker();
for (;;) {// or while(true)
System.out.println(
" Please type a word and I'll figure out if it's a palindrome(The program is case sensitive).");
isPalindrome = in.nextLine();
int length = isPalindrome.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + isPalindrome.charAt(i);
}
if (isPalindrome.equals(reverse))
System.out.println("The word that you have entered is a palindrome.");
else
System.out.println("The word that you have typed isn't a palindrome.");
System.out.print("\n Do you want to continue (y or n)?");
char answer = keyboard.next().charAt(0);
if (answer != 'y' && answer != 'Y') {
break;
}else{
aGame.play ();
}
}
}
}