【发布时间】:2020-03-05 00:12:59
【问题描述】:
Java 新手。我需要询问用户他们想要输入的字符串数量(仅由大小写字母、空格和数字组成)。这些字符串需要存储在一个数组中。然后我创建了一个布尔方法来判断这些字符串是否是回文(忽略空格和大小写)。如果它是回文,那么我添加到结果列表中以便稍后打印。我对如何要求用户输入确切数量的字符串以及如何检查每个单独的字符串感到困惑。我必须使用 StringBuilder。这就是我到目前为止所拥有的(有点乱,抱歉)。我觉得我在使用 StringBuilder/array 错误,我该如何解决这个问题?
public class Palindromes {
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
System.out.print("Enter the strings: ");
StringBuilder paliString = new StringBuilder(numOfStrings);
for(int n=0; n < paliString; n++){
paliString[n] = scan.nextLine();
scan.nextLine();
String[] stringPali = new String[numOfStrings];
StringBuilder str = paliString;
if(isPali(userString)){
paliString = append.userString;
}
System.out.println("The palindromes are: " + userString ";");
}
static boolean isPali(String userString) {
int l = 0;
int h = userString.length() - 1;
// Lowercase string
userString = userString.toLowerCase();
// Compares character until they are equal
while (l <= h) {
char getAtl = userString.charAt(l);
char getAth = userString.charAt(h);
// If there is another symbol in left
// of sentence
if (!(getAtl >= 'a' && getAtl <= 'z'))
l++;
// If there is another symbol in right
// of sentence
else if (!(getAth >= 'a' && getAth <= 'z'))
h--;
// If characters are equal
else if (getAtl == getAth) {
l++;
h--;
}
// If characters are not equal then
// sentence is not palindrome
else
return false;
}
// Returns true if sentence is palindrome
return true;
}
}
样本结果:
Enter the number of strings: 8
Enter the strings:
Race Car
Mountain Dew
BATMAN
Taco Cat
Stressed Desserts
Is Mayonnaise an instrument
swap paws
A Toyotas a Toyota
The palindromes are: Race Car; Taco Cat; Stressed Desserts; swap paws; A Toyotas a Toyota
【问题讨论】:
-
您还没有告诉我们,您面临的实际错误是什么,但我看到不少。 a) 在执行
scan.nextInt();之后执行scan.nextLine();b) 在循环中使用numOfStrings变量for int x = 0; x < numOfStrings; x++) ....c) 将StringBuilder paliString更改为使用String[]d) 只需在循环中调用isPali方法,不需要存储任何东西(这实际上消除了对c)的需要
标签: java arrays string stringbuilder palindrome