如何在没有数组的情况下在java中拆分字符串?

时间:2012-10-26 23:46:26

标签: java string split calculator

我有一个家庭作业,我需要创建一个计算器,接受这种形式的用户输入[1 + 2/3 * 5-4]。我不应该使用数组来存储字符串中的值。相反,我应该一次采取3个数字和2个运算符。我的问题是我如何存储数字和运算符,一旦我存储它们并计算值得到q新数字和原始字符串中的新运算符。这是我到目前为止还不确定我是否正确的方向。

public class ExpresionEvaluation {

    private static String expresion;
    static double o1;
    static double o2;
    private static double o3;
    private static char operator1;
    private static char operator2;

    public static double getO1(String s){
        s=s.trim();
        String r ="";
        while (s.length()>0 && s.charAt(0)>='0' && s.charAt(0)<='9'){

            r = r + s.charAt(0);
            s = s.substring(1);


        }
        o1 = Double.parseDouble(r);
        return(o1);
    }

    public static char getOperator1(String s){
        s=s.trim();
        char r;
        while (s.length()>0 && s.charAt(0)>='0' && s.charAt(0)<='9'){

            r = s.charAt(1);
            s = s.substring(2);


        }
        r = operator1;
        return(r);
    }

    public static double getO2(String s){


        s=s.trim();
        String r ="";
        while (s.length()>0 && s.charAt(0)>='0' && s.charAt(0)<='9'){

            r = r + s.charAt(2);
            s = s.substring(3);


        }
        o2 = Double.parseDouble(r);

        return(o2);
    }


    public static char getOperator2(String s){
        s=s.trim();
        char r;
        while (s.length()>0 && s.charAt(0)>='0' && s.charAt(0)<='9'){

            r = s.charAt(3);
            s = s.substring(4);


        }
        r = operator2;
        return(operator2);
    }

    public static double getO3(String s){


        s=s.trim();
        String r ="";
        while (s.length()>0 && s.charAt(0)>='0' && s.charAt(0)<='9'){

            r = r + s.charAt(4);
            s = s.substring(5);


        }
        o3 = Double.parseDouble(r);

        return(o3);
    }
}

1 个答案:

答案 0 :(得分:0)

从技术上讲,你可以通过使用集合类来绕过它。在java.util包中,有许多类可以模拟数组的行为,但是可以重新调整大小并提供更多功能。这些包括java.util.ArrayList,java.util.LinkedList,java.util.Vector(不要使用那个)和java.util.Stack。 java集合框架非常广泛,我建议阅读

中的文档

http://docs.oracle.com/javase/tutorial/collections/implementations/index.html

如果您不允许使用集合,我唯一能想到的是使用一个大字符串并在单独的部分之间插入某种特殊字符或序列,然后使用indexOf(char ,fromIndex)和substring迭代这些部分,如下所示:

   final int maxwords = 5;
   String strlist = "this@should@be@an@array@";
   int lastindex = 0, index = 0;
   for(int n= 0; n < maxwords; n ++){

             index = strlist.indexOf("@",lastindex);
             String substr = strlist.substring(lastindex,index);
             //process substring here
             System.out.println(substr);
             lastindex = index + 1;
      }

这是一种非常丑陋的做事方式,但这是我唯一能想到的。希望这会有所帮助。