gpt4 book ai didi

java - 当他/她想退出程序时如何询问用户

转载 作者:行者123 更新时间:2023-11-30 10:53:32 26 4
gpt4 key购买 nike

这是我正在开发的程序,但我在弄清楚如何通过说出一个词或数字来询问用户是否已完成该程序时遇到了问题。

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');
}
}

最佳答案

将您的整个应用程序放入循环中。一种简单的方法是将 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);
}

关于java - 当他/她想退出程序时如何询问用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33950423/

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