Advertisement
Guest User

Help please.

a guest
Sep 9th, 2015
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. public static void task1(){
  2.  
  3. //Creating a scanner for user input.
  4. Scanner sc = new Scanner(System.in);
  5. //Asking the user for a infix string
  6. System.out.println("Hi, please enter a infix string! (This program will convert it into RPN).");
  7. //Creating a variable for the infix string and also reading the value.
  8. String infix = sc.nextLine();
  9. //Creating a variable for the output.
  10. String output = "", tmp = "";
  11. //Getting the amount of characters.
  12. int length = infix.length();
  13.  
  14.  
  15. //Converting the infix string into a RPN string.
  16. for (int i = 0; i < length; i++){
  17.  
  18. char character = infix.charAt(i);
  19. if (character >= '0' && character <= '9'){
  20. output = output + character;
  21. }
  22. else if (character == '('){
  23. tmp = character + tmp;
  24. //tmp = tmp + character;
  25. }
  26. else if (character == ')'){
  27.  
  28. int j = tmp.indexOf('(');
  29. if (tmp.contains("(")){
  30. output += tmp.substring(0, j);
  31. String remove = tmp.substring(0, j+1);
  32. tmp = tmp.replace(remove,"");
  33. System.out.println(tmp);
  34. }
  35. //5+5*5*(2+10)
  36. }
  37. else if (character == '+' || character == '-' || character == '*' || character == '/'){
  38. //tmp = tmp + character;
  39.  
  40.  
  41. char t = tmp.length() > 0 ? tmp.charAt(0): ' ';
  42. while (tmp.length() > 0 && !(operatorCheck(t) > operatorCheck(character)) && t != '('){
  43. output += t;
  44. System.out.println("before delete: " + tmp);
  45. tmp = tmp.substring(0, tmp.length()-1);
  46. System.out.println("delete: " + tmp);
  47. }
  48. tmp = character + tmp;
  49. }
  50.  
  51. // test - System.out.println(infix.charAt(i));
  52. System.out.println("tmp:" + tmp);
  53. System.out.println("output" + output + "\n");
  54.  
  55. }
  56.  
  57. output += tmp;
  58. tmp = "";
  59.  
  60.  
  61.  
  62. //test print out.
  63. System.out.println("infix is: " + infix + "\n");
  64. System.out.println("infix length is: " + length + " chars.\n");
  65. System.out.println("output: " + output + "\n");
  66. System.out.println("in tmp: " + tmp + "\n");
  67.  
  68. }
  69. public static int operatorCheck(char operator){
  70. if (operator == '+' || operator == '-'){
  71. return 0;
  72. }
  73. return 1;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement