我有一个带有一元运算符的算术表达式(字符串),我想将每个元素放在一个数组中。例如:-3 + 4.2 * 5 ==>输出应为:-3,+,4.2,*,5(不是 - ,3,+,4.2,*,5) 3 + -5 ==>输出应为:3,+, - 5(使用一元运算符) (3 /(5-8)+18) 2 ==>输出应为:(,3,/,(,5, - ,8,),+,18,),, 2
这是我到目前为止尝试的代码,输出是3,+, - ,5,它没有将一元运算符放在数字的前面。
我的问题是如何将每个元素正确放入数组中。
public class Test2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Input:");
Scanner in = new Scanner(System.in);
String input = in.nextLine();
String[] arr1= splitInfixExpression(input);
for(int i=0;i<arr1.length;i++)
{
System.out.println(arr1[i]);
}
}
priva te static boolean isOperandChar(final char c) {
return Character.isDigit(c) || c == '.';
}
private static boolean isParenthesis(final char c) {
return c=='('||c==')';
}
private static String[] splitInfixExpression(final String input) {
final List<String> postfixExpression = new ArrayList<>();
boolean encounteredOperandStart = false;
String currentOperand = "";
for (final char c : input.toCharArray()) {
if (encounteredOperandStart) {
if (isOperandChar(c)) {
currentOperand += c;
}
postfixExpression.add(currentOperand);
postfixExpression.add(String.valueOf(c));
currentOperand = "";
encounteredOperandStart = false;
} else {
if (isOperandChar(c)) {
encounteredOperandStart = true;
currentOperand += c;
}
else if(isParenthesis(c)) {
postfixExpression.add(String.valueOf(c));
//currentOperand = "";
encounteredOperandStart=false;
}
else{
postfixExpression.add(String.valueOf(c));
//currentOperand = "";
encounteredOperandStart=false;
}
}
}
if (!currentOperand.isEmpty()) {
postfixExpression.add(currentOperand);
}
return postfixExpression.toArray(new String[postfixExpression.size()]);
}}
答案 0 :(得分:0)
我认为这是你想要的吗? :)
public static List<String> splitInfixExpression(String someString){
List<String> someList = new ArrayList<String>();
String tempString = "";
for (int i = 0; i < someString.length(); i++){
if (Character.isDigit(someString.charAt(i)) || (someString.charAt(i) == '-' && someString.length() == 0) || someString.charAt(i) == '.'){
tempString += String.valueOf(someString.charAt(i));
tempString = tempString.trim();
}
else{
if (tempString.length() > 0){
someList.add(tempString);
}
tempString = String.valueOf(someString.charAt(i));
if (someList.size() > 0 && Character.isDigit(someList.get(someList.size() - 1).charAt(someList.get(someList.size() - 1).length() - 1))){
someList.add(tempString);
tempString = "";
}
else if (tempString.trim().length() > 0 && ((!tempString.equals("-"))) && ((!tempString.equals("+")))){
someList.add(tempString);
tempString = "";
}
}
}
someList.add(tempString);
return someList;
}