[java] prefixtoinfix

Viewer

copydownloadembedprintName: prefixtoinfix
  1. import java.util.NoSuchElementException;
  2. import java.util.Scanner;
  3.  
  4. public class PrefixToInfix {
  5.  
  6.     public static boolean isOperator(char c) {
  7.         return c == '+' || c == '-' || c == '*' || c == '/';
  8.     }
  9.  
  10.     public static String convertPrefixToInfix(String prefix) {
  11.         StringDoubleEndedQueueImpl<String> queue = new StringDoubleEndedQueueImpl<>();
  12.         char[] prefixCharArray = prefix.toCharArray();
  13.         int N = prefixCharArray.length;
  14.  
  15.         for (int i = 0; i < N; i++) {
  16.             if (Character.isDigit(prefixCharArray[i])) {
  17.                 queue.addFirst(String.valueOf(prefixCharArray[i]));
  18.             } else if (isOperator(prefixCharArray[i])) {
  19.                 String item1 = queue.getLast();
  20.                 queue.removeLast();
  21.                 String item2 = queue.getLast();
  22.                 queue.removeLast();
  23.                 queue.addLast("(" + item2 + prefixCharArray[i] + item1 + ")");
  24.             } else {
  25.                 throw new NoSuchElementException();
  26.             }
  27.         }
  28.  
  29.         return queue.getLast();
  30.     }
  31.  
  32.     public static String convertPrefixToPostfix(String prefix) {
  33.         StringDoubleEndedQueueImpl<String> queue = new StringDoubleEndedQueueImpl<>();
  34.         char[] prefixCharArray = prefix.toCharArray();
  35.         int N = prefixCharArray.length;
  36.  
  37.         for (int i = N - 1; i >= 0; i--) {
  38.             if (Character.isDigit(prefixCharArray[i])) {
  39.                 queue.addFirst(String.valueOf(prefixCharArray[i]));
  40.             } else if (isOperator(prefixCharArray[i])) {
  41.                 String item1 = queue.getFirst();
  42.                 queue.removeFirst();
  43.                 String item2 = queue.getFirst();
  44.                 queue.removeFirst();
  45.                 queue.addFirst(item1 + item2 + prefixCharArray[i]);
  46.             } else {
  47.                 throw new NoSuchElementException();
  48.             }
  49.         }
  50.  
  51.         return queue.getFirst();
  52.     }
  53.  
  54.     public static void main(String[] args) {
  55.         Scanner myObj = new Scanner(System.in);
  56.         System.out.println("Enter prefix: ");
  57.  
  58.         String prefix = myObj.nextLine();
  59.  
  60.         // Convert prefix to infix
  61.         String infixExpression = convertPrefixToInfix(prefix);
  62.         System.out.println("Infix Expression: " + infixExpression);
  63.  
  64.         myObj.close();
  65.     }
  66. }
  67.  

Editor

You can edit this paste and save as new:


File Description
  • prefixtoinfix
  • Paste Code
  • 28 Mar-2024
  • 2.31 Kb
You can Share it: