所以我在较早的线程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.");
}
}
我好奇的部分是用粗体写的。我一直在谷歌搜索并尝试使用 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 并且可能只使用一个扫描仪(?),但我只是想看看是否有解决办法标点符号问题,因为我觉得其余的只是我自己能够弄清楚的细节。
提前致谢!