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()您从文件中读取下一个令牌并尝试i根据第一个字符串的 ( ) 长度访问该令牌的第 th 元素,current如果读取的令牌比第一个令牌短,这将导致异常

于 2012-05-26T04:11:02.700 回答