我正在制作我的第一個 java 項目,以檢查用戶輸入的單詞(沒有數字或符號)是否是回文。我使用了這里概述的方法:https : //stackoverflow.com/a/4139065/10421526作為邏輯。該代碼按請求工作,但在無效輸入后我無法重新提示用戶,因為它似乎“阻止”了我的代碼接受有效輸入的能力,打印了我的“重試”消息。我也嘗試過 do while 版本,但最終出現格式錯誤。我認為我定義 stringOut 變量的方式給我帶來了麻煩,但我不知道如何更改它而不像 eclipse 所說的那樣進行重復。這是經過數十次循環嘗試后我能得到的最接近的結果:import java.util.Scanner;public class PalindromTester { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); System.out.println("Input word to test: "); String stringIn = in.nextLine(); String stringOut = new StringBuilder(stringIn).reverse().toString(); while (!stringIn.matches("[a-zA-Z]+")) { System.out.println("Invalid input, try again."); in.next(); //stops infinite error loop } if ((stringIn.equalsIgnoreCase(stringOut))) { System.out.println("Palindrome detected"); System.out.println("You entered: " + stringIn); System.out.println("Your string reversed is: " + stringOut);} else { System.out.println("Not a palindrome");} }}
添加回答
舉報
0/150
提交
取消