如何获得令牌迭代器来组合数字

时间:2015-03-12 22:09:32

标签: java iterator expression token

我有这个代码读取表达式的每个标记。输出应该是这个。如何将数字汇总到一起?

下一个标记:[15]

下一个标记:[*]

下一个标记:[(]

下一个标记:[26]
等....

但我得到了这个......

下一个标记:[1]

下一个标记:[5]

下一个标记:[*]

下一个标记:[(]

下一个标记:[2]

下一个标记:[6]

import java.util.Iterator;
import java.util.Scanner;


public class TokenIter implements Iterator<String>{

// This class builds a Token Iterator, that produces 
// Strings containing numbers (sequences of digits) and 
// special characters: "(" ")" "+" "-"  "*" "/"

//input line to be tokenized
private String line;

// the next Token, null if no next Token
private String nextToken;

public TokenIter(String line){
    this.line = line;
}
static int counter = 0;

public void remove() {
    // TODO Auto-generated method stub
    throw new UnsupportedOperationException();
}


public static void main(String[] args){
    String line = "  15*(26+37) - 432/5*61 - (321-1234567)   ";
    System.out.println("line: [" + line + "]");
    TokenIter tokIt = new TokenIter(line);
    // print tokens in square brackets to check absence of white space
    while(tokIt.hasNext()){
        if (tokIt.next() != "no")
            System.out.println("next token: [" + tokIt.next() + "]");

        else
        {

        }
        counter++;

    }   
}
public boolean hasNext(){ 
    if (counter < line.length())
    {
        return true;
    }
    else 
    {
        return false;
    }
}

//char c;

public String next() {
    //String L = line.trim();
    String s = "";
    //  for (int index =0; index < L.length(); index++){
    if (!hasNext())
        return null;
    else{
        {
            char c = line.charAt(counter);
            if( c == ('/'))
            {
                counter = counter++;
                s = "" + c;
                return s;
            }
            if( c == ('+'))
            {
                counter = counter++;
                s = "" + c;
                return s;
            }
            if( c == ('*'))
            {
                counter = counter++;
                s = "" + c;
                return s;
            }
            if( c == ('-'))
            {
                counter = counter++;
                s = "" + c;
                return s;
            }
            if( c == ('('))
            {
                counter = counter++;
                s = "" + c;
                return s;
            }
            if( c == (')'))
            {
                counter = counter++;
                s = "" + c;
                return s;
            }
            else if (c == ' ')
            {
                counter = counter++;
                return "no";
            }

            else if (c == ('0'|'1'| '2' | '3'|'4'|'5'| '6'| '7' |'8' | '9'))
            {
                counter = counter++;
                return s;
            }
            else if (Character.isDigit(c)){
                if((c == '0') || (c == '1') ||(c == '2') ||(c == '3') ||(c == '4') ||(c == '5') ||(c == '6') ||(c == '7') ||(c == '8') || (c == '9'))
                    counter = counter++;
                s += "" + c;
                return s;
            }
        }
    }
    return s;
}}

2 个答案:

答案 0 :(得分:0)

您似乎正在尝试构建一个更加简洁的数学表达式。有很多方法可以实现这一目标。一种方法是使用String tokenizer并设置分隔符:

public String nextToken(String delim)

但是,不再使用字符串标记符类。分割方法是推荐的方法。

答案 1 :(得分:0)

这可以通过一些正则表达式魔术轻松完成。想法是你要分割字符串,但也保留分隔符。这可以通过向前看或向后看而完成,但是分隔符最终连接到一侧或另一侧。要解决这个问题,您需要同时使用它们。这将导致分隔符作为单独的标记返回。

// Define the characters to split on: ' ', '+', '-', '*', '\', '(', ')'
final String splitOn = "\\+|-|\\*|/|\\(|\\)";
final String lookAheadGroup = "(?=" + splitOn + ")";
final String lookBehindGroup = "(?<=" + splitOn + ")";
final String regex = "(" + lookBehindGroup + "|" + lookAheadGroup + ")";

此正则表达式可与String.split()

一起使用
String line = "  15*(26+37) - 432/5*61 - (321-1234567)   ";
String[] tokens = line.split(regex);
for (String token : tokens) {
    System.out.printf("'%s'\n", token);
}

或使用扫描仪

System.out.println("\n\nScanner");
Scanner scanner = new Scanner(line);
scanner.useDelimiter(regex);

while(scanner.hasNext()) {
    System.out.printf("'%s'\n", scanner.next());
}
scanner.close();

示例输出

请注意,令牌没有额外的空白区域,因此如果您的后期处理对它敏感,您将不得不这样做。

'15', '*', '(', '26', '+', '37', ')', ' ', '-', ' 432', '/', '5', '*', '61 ', '-', ' ', '(', '321', '-', '1234567', ')',