为什么我的分裂方法不像预期的那样工作,当我从操作符分裂数字



代码输出

public class Model {
private Scanner sc = new Scanner(System.in);
private String expression;
private String exp[];

public Model()
{
expression = sc.nextLine();
split();
}

public void split()
{

//splitting the entered expression to array of operators alone and array of the numbers then create Arraylist to combine the operators and numbers together as if it is a string expression  but as an array
String num[]= this.expression.split("[/+/*/-]");
String preop[]= this.expression.split("[0123456789]"); // this will give [empty, operator, operator...] therefore we will create another array to fill in the ops excluding empty


System.out.println("Test: Printing num Array");
for(int i = 0; i<num.length;i++)
{
System.out.print(num[i]+",");
}
System.out.println("nTest: Printing preOp Array");
for(int i = 0; i<preop.length;i++)
{
System.out.print(preop[i]+ ",");
}



ArrayList<String> op = new ArrayList<>();//I used arraylist because easier
for(int i = 1; i<preop.length;i++)
{
op.add(preop[i]);
}

System.out.println("nTest of the fixed preOp array: " + op);


//putting the operands and the operators together in the same array

ArrayList<String> exp = new ArrayList<>();
//fill the arraylist with numbers then add the operators to it by using number (index of the operator +1 +count)
for(int i = 0; i <num.length;i++)
{
exp.add(num[i]);
}
int count = 0;
for(int i = 0; i <op.size();i++)
{
exp.add(i+1+count, op.get(i));
count++;
}

System.out.println("Test: " + exp);
}

问题是,当用户在表达式中输入双位数时,op数组将给出空槽[op, op, empty, op]。

我期待类似的结果,当用户输入一个数字,它给出预期的结果,在图像输入与一个数字

这是因为

this.expression.split("[0123456789]");

你被一个单位数分割,所以43也被分成两部分,中间有一个空字符串。同样,你不需要在正则表达式中命名所有的数字,你可以只做一个范围"[0-9]"。如果要匹配1位或更多位,请添加+。这应该可以工作:

this.expression.split("[0-9]+");

您可以使用regex在任何操作符处拆分并使用前向和后向保持它们:

public static void main(String[] args) {
String first  = "3+2*3-4";
String second = "3+2-43*3";
System.out.println(Arrays.toString(splitExpression(first)));
System.out.println(Arrays.toString(splitExpression(second)));
}
static String[] splitExpression(String input){
String regex = "((?<=(\+|\-|\*|\/))|(?=(\+|\-|\*|\/)))";
return input.split(regex);
}

输出:

[3, +, 2, *, 3, -, 4]
[3, +, 2, -, 43, *, 3]

最新更新