我正在尝试创建一个程序来读取文件并检查文本是否为回文。代码编译,但并没有真正起作用。
问题是我不知道如何将一个完整的标记分解成字符或将其分配给一个字符串,以便使用字符串的长度来推送
(排队)每个字母或数字到堆栈
(队列)。谁能为此提出解决方案?
public static void main(String [] args) throws IOException{
StackReferenceBased stack = new StackReferenceBased();
QueueReferenceBased queue = new QueueReferenceBased();
Scanner s = null;
String fileName=args[0]+".txt";
int symbols = 0;
int lettersAndDigits =0;
int matches = 0;
try{
s = new Scanner(new File(fileName));
while(s.hasNext()){
String current = s.next();
for(int i=0;i<current.length();i++){
char temp = s.next().charAt(i);
if(Character.isLetterOrDigit(temp)){
stack.push(temp);
queue.enqueue(temp);
lettersAndDigits++;
}
else {
symbols++;
}
}
}
System.out.println("There are: " + " "+ symbols + " " +"symbols and " + " "+lettersAndDigits + " "+ "digits/letters");
}
catch (FileNotFoundException e) {
System.out.println("Could not open the file:" + args[0]);
} //catch (Exception e) {
//System.out.println("ERROR copying file");
finally {
if(s != null){
s.close();
}
}
while (!stack.isEmpty()){
if(!stack.pop().equals(queue.dequeue())){
System.out.println("not pali");
break;
}
else {
++matches;
}
}
if(matches==lettersAndDigits){
System.out.print("pali");
}
}
最佳答案
代替
char temp = s.next().charAt(i);
你需要
char temp = current.charAt(i);
通过调用 s.next()
,您可以从文件中读取下一个标记,并尝试根据第一个字符串的 (current
) length,如果读取的token比第一个stoken短会导致异常
关于java 将 next() 分配给字符串或分成字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10763478/