Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void task1(){
- //Creating a scanner for user input.
- Scanner sc = new Scanner(System.in);
- //Asking the user for a infix string
- System.out.println("Hi, please enter a infix string! (This program will convert it into RPN).");
- //Creating a variable for the infix string and also reading the value.
- String infix = sc.nextLine();
- //Creating a variable for the output.
- String output = "", tmp = "";
- //Getting the amount of characters.
- int length = infix.length();
- //Converting the infix string into a RPN string.
- for (int i = 0; i < length; i++){
- char character = infix.charAt(i);
- if (character >= '0' && character <= '9'){
- output = output + character;
- }
- else if (character == '('){
- tmp = character + tmp;
- //tmp = tmp + character;
- }
- else if (character == ')'){
- int j = tmp.indexOf('(');
- if (tmp.contains("(")){
- output += tmp.substring(0, j);
- String remove = tmp.substring(0, j+1);
- tmp = tmp.replace(remove,"");
- System.out.println(tmp);
- }
- //5+5*5*(2+10)
- }
- else if (character == '+' || character == '-' || character == '*' || character == '/'){
- //tmp = tmp + character;
- char t = tmp.length() > 0 ? tmp.charAt(0): ' ';
- while (tmp.length() > 0 && !(operatorCheck(t) > operatorCheck(character)) && t != '('){
- output += t;
- System.out.println("before delete: " + tmp);
- tmp = tmp.substring(0, tmp.length()-1);
- System.out.println("delete: " + tmp);
- }
- tmp = character + tmp;
- }
- // test - System.out.println(infix.charAt(i));
- System.out.println("tmp:" + tmp);
- System.out.println("output" + output + "\n");
- }
- output += tmp;
- tmp = "";
- //test print out.
- System.out.println("infix is: " + infix + "\n");
- System.out.println("infix length is: " + length + " chars.\n");
- System.out.println("output: " + output + "\n");
- System.out.println("in tmp: " + tmp + "\n");
- }
- public static int operatorCheck(char operator){
- if (operator == '+' || operator == '-'){
- return 0;
- }
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement