所以我在早期線程Java, Check if a String is a palindrome. Case insensitive中詢問了有關讀取字符串的字符串。我收到了很多很好的反饋,並做了我的功課(學到了很多!),但由於它是一個實驗任務(大學),我無法使用所提出的方法(字符串生成器)。下面的代碼(至少是大綱)是我爲這個任務編寫代碼的方式,所以這不是關於方法的問題。Java - 分隔符忽略句尾的標點符號
import java.util.*;
public class Lab04 {
public static void main(String[] args) {
// declaring variables
String sentence;
String word;
// initiating the scanner
Scanner keyboard = new Scanner(System.in);
// prompting the user for a sentence
System.out.println("Please enter the sentence: ");
sentence = keyboard.nextLine();
System.out.println("Your input was: " + '"' + sentence + '"');
// checking if it is a palindrome
sentence = sentence.toLowerCase();
Scanner stringScan = new Scanner(sentence);
**stringScan.useDelimiter("[ \t\n,.-:;'?!\"] + ");**
char leftChar, rightChar;
boolean isPalindrome = true;
while (stringScan.hasNext()) {
word = stringScan.next();
leftChar = word.charAt(0);
rightChar = word.charAt(word.length() - 1);
if (!(leftChar == rightChar))
isPalindrome = false;
}
if (isPalindrome)
System.out.println("This is a palindrome.");
else
System.out.println("This is not a palindrome.");
// checking if it is an alliteration
sentence = sentence.toLowerCase();
Scanner stringScan1 = new Scanner(sentence);
**stringScan1.useDelimiter("[ \t\n,.-:;'?!\"]+");**
char firstChar = sentence.charAt(0);
boolean isAlliteration = true;
while (stringScan1.hasNext()) {
word = stringScan1.next();
if (firstChar != word.charAt(0) && word.length() > 3)
isAlliteration = false;
}
if (isAlliteration)
System.out.println("This is an alliteration.");
else
System.out.println("This is not an alliteration.");
}
}
我很好奇的部分是用粗體書寫的。我一直在使用googling並嘗試使用Java文檔,但我很難找出分隔符的格式是如何工作的。
當前分隔符可能是凌亂的,並且包含不必要的字符。
我的目標是在最後使分隔符忽略標點符號。它已經接近完美了,但我需要在最後找到一種忽略標點符號的方法;
實施例:
輸入:
Doc, note, I dissent. A fast never prevents a fatness. I diet on cod
輸出:
Your input was: "Doc, note, I dissent. A fast never prevents a fatness. I diet on cod"
This is a palindrome.
輸入:
Doc, note, I dissent. A fast never prevents a fatness. I diet on cod.
輸出:
Your input was: "Doc, note, I dissent. A fast never prevents a fatness. I diet on cod"
This is not a palindrome.
至於其餘代碼:
我一直在嘗試幾個不同的東西,所以有一些「額外」的代碼,就像我不需要再使用sentence.toLowerCase並很可能只是用一臺掃描儀(?),但我只想看看是否有對標點符號問題的解決方法,因爲我覺得其餘的只是我能夠弄清楚自己的細節。
在此先感謝!
我不想成爲壞消息的持有者..但該程序實際上並不檢查句子是否是迴文。它檢查每個單詞的第一個和最後一個字符是否相同。 – 2013-03-19 03:50:34
例如,如果您鍵入:'abcdefga'它會說這是一個迴文。對於您的實際迴文檢查,您必須使用循環檢查所有字母。或者你可以扭轉字符串,並檢查反向字符串和原始字符串是否相同 – 2013-03-19 03:59:13
哦,謝謝我沒有意識到這一點!我會馬上解決它.. – user2121604 2013-03-19 04:08:02