【发布时间】:2022-01-03 11:52:35
【问题描述】:
我的代码将带有右括号“)”的表达式组合成一个完整的带有右括号“(”的表达式组合。如果右括号和左括号仍然不相等,则使第一个表达式最后一个优先级,如果仍然不相等,则对第一个索引进行左括号。最多三个表达式(表达式=数字运算符数字)。
示例输入: 4 + 3 ) * 4 - 2 ) * 6 - 6 ) ) )
样本输出: ((4 + 3 ) * ((4 - 2 ) * (6 - 6 ) ) )
我的代码在只放置 1-2 个右括号时有效。如果超过两个,程序就会挂起。
源代码:
import java.util.Scanner;
import java.lang.String;
public class brackets { //Declaration of Variables
static String Str, Strr="";
static Integer ope=0;
static int temp=0,lent,pr=0,prl=0,prr=0; //Temp = Opening Brackets placed, lent = string length, pr=Closing Brackets, prl = number of opening brackets made from last index, prr=TBA
static Scanner scan = new Scanner(System.in);
public static void main(String[]args){
System.out.println("Enter the combined experessions: ");
Str = scan.nextLine();
lent = Str.length(); //Setting the full expression to a string (Str)
for(int i=0; i<lent;i++){ //Finding how many Closing Brackets There are
if(Str.charAt(i)==')'){
pr++;
}
}
Popping(lent); //Method
System.out.print(Strr); //Printing Final Ouput
scan.close();
}
public static void Popping(int lent){
for(int j =lent-1; j>-1;j--){ //I set j to lent because I want to search from rightmost to leftmost
if(Str.charAt(j)==')') //I need to find a closing bracket first before the program could start to input an opening bracket
prr++;
if(prr>0){
if(Str.charAt(j)=='+'||Str.charAt(j)=='-'||Str.charAt(j)=='*'||Str.charAt(j)=='/'||(j<=lent-2&&Character.isDigit(Str.charAt(j+1))&&Str.charAt(j)==')')){ //Finding an operator or finding a closing bracket which has a digit next to it
ope++;
}
if(ope==2){ //finding two operators mean that I can now put an opening bracket
Strr = '('+Strr;
temp++;
ope=0;
}
}
Strr = Str.charAt(j)+Strr;
if(prr>0){
if(j==0&&temp!=pr){ //If J==0 and Closing brackets still is not equal to Opening Brackets, I'll set opening bracket to the 0 index
Strr = '('+Strr;
temp++;
}
}
}
while(temp!=pr) { // If still not equal, I'll set an opening bracket to the second opening bracket there is, making the last two expression a priority
for(int j =lent-1; j>-1;j--){
if(Str.charAt(j)=='(')
prl++;
if(prl>1&&Str.charAt(j)=='('){
Strr= Strr.substring(0,j-1)+'('+Strr.substring(j,lent-1);
temp++;
}
}
}
}
}
【问题讨论】:
标签: java string search java.util.scanner brackets