如何使用stringtokenizer类

hfyxw5xn  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(230)

我应该通过使用stringtokenizer类将字符串拆分为标记来计算字符串。之后,我应该使用“integer.parseint”将这些标记转换为int值。
我不明白的是我应该如何处理分裂后的代币。

public class Tester {

    public static void main(String[] args) {
    String i = ("2+5");
    StringTokenizer st = new StringTokenizer(i, "+-", true);
    while (st.hasMoreTokens()) {
        System.out.println(st.nextToken());
    }
    int x = Integer.parseInt();
//what exactly do I have to type in here, do convert the token(s) to an int value?
}

}

如果我现在明白了,我有三个记号。那就是:“2”、“+”和“5”。
如何将这些标记转换为int值?我必须分别转换它们吗?
感谢您的帮助。

gojuced7

gojuced71#

为了能够使用从字符串中提取的整数进行一些计算,必须将它们放入arraylist中。您必须使用try/catch操作来避免numberformatexception。此外,您还可以直接从arraylist获取值,并根据需要使用它们。例如:

public static void main(String[] args) {
    ArrayList <Integer> myArray = new ArrayList <>();    
    String i = ("2+5");
        StringTokenizer st = new StringTokenizer(i, "+-/*=", true);
        while (st.hasMoreTokens()) {
            try {
            Integer stg = Integer.parseInt(st.nextToken(i));
            myArray.add(stg);
                }
            catch (NumberFormatException nfe) {};
            }

       System.out.println("This is an array of Integers: " + myArray);
       for (int a : myArray) {
           int x = a;
           System.out.println("This is an Integer: " + x);
       }
       int b = myArray.get(0);
       int c = myArray.get(1);
       System.out.println("This is b: " + b);
       System.out.println("This is c: " + c);
       System.out.println("This is a sum of b + c: " + (b + c));

}

因此,您将得到:

This is an array of Integers: [2, 5]
This is an Integer: 2
This is an Integer: 5
This is b: 2
This is c: 5
This is a sum of b + c: 7
wtlkbnrh

wtlkbnrh2#

也许你可以用这个:

String i = ("2+5");
    StringTokenizer st = new StringTokenizer(i, "+-", true);
    while (st.hasMoreTokens()) {
        String tok=st.nextToken();
        System.out.println(tok);

        //what exactly do I have to type in here, do convert the token(s) to an int value?
        if ("+-".contains(tok)) {
            //tok is an operand
        }
        else {
            int x = Integer.parseInt(tok);
        }       
    }

相关问题