作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写一个方法,该方法将查看字符串并将字符串中的任何数字添加到 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/
我是一名优秀的程序员,十分优秀!