我在Stack stack = new Stack(str.length());
为什么这不起作用?
import java.util.Scanner;
/*/
This progrma will read string and return if the string is
palindrome word, phrase, sentence or not. if the word is not palindrome
the progrma will pritn out false otherwise the progrma will print out true.
*/
public class PalindromeDemo
{
public static boolean isPalindrome(String str)
{
boolean isPal = true;
//creating stack
Stack stack = new Stack(str.length());
//push all character into stack
for(int i=0; i<str.length(); i++)
{
stack.push(str.charAt(i));
}
// now traverse str and check current character with top of stack
for(int i=0; i<str.length(); i++)
{
char c = (char) stack.pop();
// if not equal, break
if(Character.toLowerCase(c) != Character.toLowerCase(str.charAt(i)))
{
isPal = false;
break;
}
}
return isPal;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str;
System.out.println("Enter a string: ");
str = sc.nextLine();
System.out.println(isPalindrome(str));
}
}
答案 0 :(得分:1)
我在
上找不到符号错误Stack stack = new Stack(str.length());
您似乎忘记了Stack
的导入声明:
import java.util.Stack;
然后你会有另一个错误,因为Stack
只有一个无参数构造函数,它不能像你的代码那样采用int
参数。解决方法是简单地删除参数:
Stack stack = new Stack();
除此之外,除了一些不好的做法之外,你的程序似乎还在起作用:
Stack
,Stack<Character>
会更好Stack
,您应该使用Deque
和ArrayDeque
来代替i
- 和str.length() - i - 1
- 字母