2012-05-26 89 views
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"); 
    } 
    } 
+0

這是功課嗎?否則,你只是爲了檢查字符串是否是迴文而做太多。 –

+0

是的,它的任務:) – Rennos

回答

1

而不是

char temp = s.next().charAt(i); 

你需要

char temp = current.charAt(i); 

通過調用s.next()你從文件中讀取下一個標記,並嘗試訪問基礎上,該令牌的i個元素第一個字符串的長度(current),如果讀取的令牌比第一個令牌短,會導致異常

+0

哦,非常感謝!下次應該仔細閱讀我的代碼:) – Rennos