gpt4 book ai didi

java - 循环遍历字符串来检查值。 (Java计算器)

转载 作者:行者123 更新时间:2023-12-01 13:42:27 26 4
gpt4 key购买 nike

我正在尝试编写一个方法,该方法将查看字符串并将字符串中的任何数字添加到 calcOperand 数组中,并将任何运算符添加到 calcOperator 数组中。这是我的 Javat 计算器。

下面是我遇到的代码。您可以看到,我尝试创建将 String 拆分为数组并循环遍历它的方法。然后我想检查 String 以查看它是运算符还是操作数。最好的方法是什么?

import java.util.*;
public class stringCalculator {

private String userinput;
private int[] calcOperator;
private char[] calcOperand;

public stringCalculator(String userinput){
this.userinput = userinput;
//System.out.println(userinput);
}

//This function will check the input and return true if the user enters a correct expression.
public boolean checkInput(){
boolean show = userinput.matches("[-+/*0-9]+");
return show;
}

//This function will add any numbers in the string to the calcOperand array.
//and any operators to the calcOperator field.
public void parseInput(){
String[] theinput = userinput.split("");

for (int i = 0 ; i < theinput.length ; i++){
if(theinput.charAt(i) == "+" ){
calcOperator.add("+");
}
}
}
}

最佳答案

将 calcOperand 数组运算符中的操作数存储在 checkInput() 方法中的 calcOperator 数组中,如下所示:

public stringCalculator(String userinput) {
this.userinput = userinput;
checkInput();
}

// This function will check the input and return true if the user enters a
// correct expression.
public boolean checkInput() {
String[] operators = userinput.split("[-+/*]");
calcOperator = new int[operators.length];
for (int i = 0; i < calcOperator.length; i++) {
calcOperator[i] = Integer.parseInt(operators[i]);
}
String[] operands = userinput.split("[0-9]");
calcOperand = new char[operands.length];
for (int i = 0; i < operands.length; i++) {
if (operands[i].length() > 0) {
calcOperand[i] = operands[i].charAt(0);
}
}
return true;
}

关于java - 循环遍历字符串来检查值。 (Java计算器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20608749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com