[英]Palindrome checker for Java
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String word;
String c;
int x, count, count1;
System.out.println("Please enter a word:");
word=in.nextLine();
x=word.length();
count1=x;
for(count=0;count<x;count++) {
c=word.substring((count1)-1,count1);
System.out.print(c);
count1--;
}`
}
大家好,在我制作這個向后打印出一個單詞的代碼之前,但現在我想知道如何將它變成回文檢查器,但我很困惑,因為最終產品實際上是由一堆字符串 c 組成的單詞 put在一起,所以我不知道如何將它與輸入的原始單詞進行比較。 幫助?
從方法簽名和從中返回的值開始:
private boolean isPalindrome(String word1, String word2) {
boolean isPalindrome = true; // let's initiate it to true
// ...
return isPalindrome;
}
然后,你可以使用你已經擁有的(我評論了不需要的部分:
x=word.length();
for(count=0;count<x;count++) {
// c=word.substring((count1)-1,count1);
// you can use word.charAt(count); instead
// System.out.print(c);
//count1--;
}`
在循環內,將word1.charAt(count)
與word2.charAt(count)
isPalindrome
,如果它們不匹配, word2.charAt(count)
更改為 true。
您可能還想先檢查兩個字符串的長度是否相同。
編輯:添加另一種簡單的方法來檢查回文:
public static boolean isPalindrom(String s) {
return new StringBuilder(s).reverse().toString().equals(s);
}
如果您不允許使用 StringBuilder(我稍微更改了您現有的代碼),我會看到其他兩種可能性可以將其轉換為回文檢查器
將字符串前半部分的字符與后半部分的字符進行比較,如下所示:
boolean isPalindrom = true; for (int i= 0; i < (word.length()-1)/2; i++) { if(word.charAt(i) != word.charAt(word.length()-1-i)) { isPalindrom = false; } } System.out.println(word + " is a palindrom: " + isPalindrom);
或者
使用反轉的字符串,將其保存到另一個String
變量,然后檢查它是否等於您的單詞。 像這樣的東西:
public static void main(String[] args) { Scanner in = new Scanner(System.in); String word; System.out.println("Please enter a word:"); word = in.nextLine(); String reverseString = ""; for (int i = 0; i < word.length(); i++) { reverseString = reverseString + word.charAt(word.length()-1-i);; } System.out.println("original: " + word + ", reversed: " + reverseString); boolean isPalindrom = word.equals(reverseString); System.out.println(word + " is a palindrom: " + isPalindrom); }
也許這對你也有幫助: 檢查回文字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.