2

ファイルを読み取り、テキストが回文かどうかをチェックするプログラムを作成しようとしています。コードはコンパイルされますが、実際には機能しません。

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");
    }  
  }
4

1 に答える 1

1

それ以外の

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

あなたが必要

char temp = current.charAt(i); 

を呼び出すことにより、ファイルから次のトークンを読み取り、最初の文字列 ( ) の長さに基づいてそのトークンs.next()の th 要素にアクセスしようとします。これにより、読み取られたトークンが最初のトークンよりも短い場合に例外が発生します。icurrent

于 2012-05-26T04:11:02.700 に答える