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

而不是

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

你需要

char temp = current.charAt(i); 

通过调用s.next(),您可以从文件中读取下一个令牌,并尝试根据第一个字符串的长度访问该令牌的第i个元素(current),如果读取的令牌短于第一个令牌,这将导致异常

最新更新