2
我試圖創建一個程序來讀取文件並檢查文本是否是迴文。代碼編譯,但沒有真正的工作。java將next()分配給字符串或分解爲字符
問題是我不知道如何將完整的標記分解爲字符或將其分配給字符串,以便使用字符串的長度將push
(排隊)的每個字母或數字放入stack
(隊列)中。任何人都可以爲此提出解決方案嗎?
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");
}
}
這是功課嗎?否則,你只是爲了檢查字符串是否是迴文而做太多。 –
是的,它的任務:) – Rennos