请检查我的逻辑错误

时间:2014-12-07 17:01:51

标签: java

如果输入为x = y + 5

输出必须是:

Token 1 is x is identifier
Token 2 is =
Token 3 is y is identifier
Token 4 is +
Token 5 is 5

这是我做的代码我不知道我的if条件有什么问题!!

char[] ident = {'x','y','z','a','b','c','k'};

Scanner sc = new Scanner(System.in);
System.out.println("Please Enter Your String");
String x = sc.nextLine();


StringTokenizer t = new StringTokenizer(x);

for (int k = 0; k < ident.length; k++) {
    for (int j = 1; j < x.length()+1; j++) {
        char m = x.charAt(j);


        if (m==ident[k]) {

            System.out.println("Token " + j + " is " + t.nextToken()+" is identifier");

        } else {
            System.out.println("Token " + j + " is " + t.nextToken());
        }

    }

}

1 个答案:

答案 0 :(得分:0)

你不需要两个循环nether StringTokenizer。你可以这样做:

final String str = new String(ident);
char m;
for (int j = 0; j < x.length(); j++) {
    m = x.charAt(j);
    if (str.indexOf(m) >= 0) {
       System.out.println("Token " + j + " is " + m+" is identifier");
    } else {
       System.out.println("Token " + j + " is " + m);
    }
}